blob: 17ce7ac3489a9c82c639e739f308ea84fac1fd77 [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
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000221/// \brief If Expr is a valid integer constant, get the value of the integer
222/// expression and return success or failure. May output an error.
223static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
224 const Expr *Expr, uint32_t &Val,
225 unsigned Idx = UINT_MAX) {
226 llvm::APSInt I(32);
227 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
228 !Expr->isIntegerConstantExpr(I, S.Context)) {
229 if (Idx != UINT_MAX)
230 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
231 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
232 << Expr->getSourceRange();
233 else
234 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
235 << Attr.getName() << AANT_ArgumentIntegerConstant
236 << Expr->getSourceRange();
237 return false;
238 }
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000239
240 if (!I.isIntN(32)) {
Aaron Ballman31f42312014-07-24 14:51:23 +0000241 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
242 << I.toString(10, false) << 32 << /* Unsigned */ 1;
Aaron Ballmanadfdde52014-07-22 14:09:34 +0000243 return false;
244 }
245
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +0000246 Val = (uint32_t)I.getZExtValue();
247 return true;
248}
249
George Burgess IVe3763372016-12-22 02:50:20 +0000250/// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
251/// that the result will fit into a regular (signed) int. All args have the same
252/// purpose as they do in checkUInt32Argument.
253static bool checkPositiveIntArgument(Sema &S, const AttributeList &Attr,
254 const Expr *Expr, int &Val,
255 unsigned Idx = UINT_MAX) {
256 uint32_t UVal;
257 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
258 return false;
259
George Burgess IVa8049572016-12-22 19:00:31 +0000260 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
George Burgess IVe3763372016-12-22 02:50:20 +0000261 llvm::APSInt I(32); // for toString
262 I = UVal;
263 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
264 << I.toString(10, false) << 32 << /* Unsigned */ 0;
265 return false;
266 }
267
268 Val = UVal;
269 return true;
270}
271
Aaron Ballmanfb763042013-12-02 18:05:46 +0000272/// \brief Diagnose mutually exclusive attributes when present on a given
273/// declaration. Returns true if diagnosed.
274template <typename AttrTy>
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000275static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
276 IdentifierInfo *Ident) {
Aaron Ballman2cfbc002014-01-03 16:23:46 +0000277 if (AttrTy *A = D->getAttr<AttrTy>()) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +0000278 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
279 << A;
280 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
Aaron Ballmanfb763042013-12-02 18:05:46 +0000281 return true;
282 }
283 return false;
284}
285
Alp Toker601b22c2014-01-21 23:35:24 +0000286/// \brief Check if IdxExpr is a valid parameter index for a function or
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000287/// instance method D. May output an error.
288///
289/// \returns true if IdxExpr is a valid index.
Alp Toker601b22c2014-01-21 23:35:24 +0000290static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
291 const AttributeList &Attr,
292 unsigned AttrArgNum,
293 const Expr *IdxExpr,
294 uint64_t &Idx) {
David Majnemer06864812015-04-07 06:01:53 +0000295 assert(isFunctionOrMethodOrBlock(D));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000296
297 // In C++ the implicit 'this' function parameter also counts.
298 // Parameters are counted from one.
Aaron Ballmanbe50eb82013-07-30 00:48:57 +0000299 bool HP = hasFunctionProto(D);
300 bool HasImplicitThisParam = isInstanceMethod(D);
301 bool IV = HP && isFunctionOrMethodVariadic(D);
Alp Toker601b22c2014-01-21 23:35:24 +0000302 unsigned NumParams =
303 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000304
305 llvm::APSInt IdxInt;
306 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
307 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000308 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
309 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
310 << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000311 return false;
312 }
313
314 Idx = IdxInt.getLimitedValue();
Alp Toker601b22c2014-01-21 23:35:24 +0000315 if (Idx < 1 || (!IV && Idx > NumParams)) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000316 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
317 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000318 return false;
319 }
320 Idx--; // Convert to zero-based.
321 if (HasImplicitThisParam) {
322 if (Idx == 0) {
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000323 S.Diag(Attr.getLoc(),
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000324 diag::err_attribute_invalid_implicit_this_argument)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +0000325 << Attr.getName() << IdxExpr->getSourceRange();
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000326 return false;
327 }
328 --Idx;
329 }
330
331 return true;
332}
333
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000334/// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
335/// If not emit an error and return false. If the argument is an identifier it
336/// will emit an error with a fixit hint and treat it as if it was a string
337/// literal.
Tim Northover6a6b63b2013-10-01 14:34:18 +0000338bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
339 unsigned ArgNum, StringRef &Str,
Tim Northovera484bc02013-10-01 14:34:25 +0000340 SourceLocation *ArgLocation) {
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000341 // Look for identifiers. If we have one emit a hint to fix it to a literal.
342 if (Attr.isArgIdent(ArgNum)) {
343 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
Tim Northover6a6b63b2013-10-01 14:34:18 +0000344 Diag(Loc->Loc, diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000345 << Attr.getName() << AANT_ArgumentString
346 << FixItHint::CreateInsertion(Loc->Loc, "\"")
Craig Topper07fa1762015-11-15 02:31:46 +0000347 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000348 Str = Loc->Ident->getName();
349 if (ArgLocation)
350 *ArgLocation = Loc->Loc;
351 return true;
352 }
353
354 // Now check for an actual string literal.
355 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
356 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
357 if (ArgLocation)
358 *ArgLocation = ArgExpr->getLocStart();
359
360 if (!Literal || !Literal->isAscii()) {
Tim Northover6a6b63b2013-10-01 14:34:18 +0000361 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
Aaron Ballman3b1dde62013-09-13 19:35:18 +0000362 << Attr.getName() << AANT_ArgumentString;
363 return false;
364 }
365
366 Str = Literal->getString();
367 return true;
368}
369
Aaron Ballman6f9165a2013-11-27 15:24:06 +0000370/// \brief Applies the given attribute to the Decl without performing any
371/// additional semantic checking.
372template <typename AttrType>
373static void handleSimpleAttribute(Sema &S, Decl *D,
374 const AttributeList &Attr) {
375 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
376 Attr.getAttributeSpellingListIndex()));
377}
378
Justin Lebar3eaaf862016-01-13 01:07:35 +0000379template <typename AttrType>
380static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
381 const AttributeList &Attr) {
382 handleSimpleAttribute<AttrType>(S, D, Attr);
383}
384
385/// \brief Applies the given attribute to the Decl so long as the Decl doesn't
386/// already have one of the given incompatible attributes.
387template <typename AttrType, typename IncompatibleAttrType,
388 typename... IncompatibleAttrTypes>
389static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
390 const AttributeList &Attr) {
391 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
392 Attr.getName()))
393 return;
394 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
395 Attr);
396}
397
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000398/// \brief Check if the passed-in expression is of type int or bool.
399static bool isIntOrBool(Expr *Exp) {
400 QualType QT = Exp->getType();
401 return QT->isBooleanType() || QT->isIntegerType();
402}
403
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000404
405// Check to see if the type is a smart pointer of some kind. We assume
406// it's a smart pointer if it defines both operator-> and operator*.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000407static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
Richard Smithcf4bdde2015-02-21 02:45:19 +0000408 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
409 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
David Blaikieff7d47a2012-12-19 00:45:41 +0000410 if (Res1.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000411 return false;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000412
Richard Smithcf4bdde2015-02-21 02:45:19 +0000413 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
414 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
David Blaikieff7d47a2012-12-19 00:45:41 +0000415 if (Res2.empty())
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000416 return false;
417
418 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000419}
420
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000421/// \brief Check if passed in Decl is a pointer type.
422/// Note that this function may produce an error message.
423/// \return true if the Decl is a pointer type; false otherwise
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000424static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
425 const AttributeList &Attr) {
Aaron Ballman553e6812013-12-26 14:54:11 +0000426 const ValueDecl *vd = cast<ValueDecl>(D);
427 QualType QT = vd->getType();
428 if (QT->isAnyPointerType())
429 return true;
430
431 if (const RecordType *RT = QT->getAs<RecordType>()) {
432 // If it's an incomplete type, it could be a smart pointer; skip it.
433 // (We don't want to force template instantiation if we can avoid it,
434 // since that would alter the order in which templates are instantiated.)
435 if (RT->isIncompleteType())
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000436 return true;
DeLesley Hutchinse09be232012-04-23 18:39:55 +0000437
Aaron Ballman553e6812013-12-26 14:54:11 +0000438 if (threadSafetyCheckIsSmartPointer(S, RT))
439 return true;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000440 }
Aaron Ballman553e6812013-12-26 14:54:11 +0000441
442 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
Aaron Ballman68289452013-12-26 15:06:01 +0000443 << Attr.getName() << QT;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +0000444 return false;
445}
446
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000447/// \brief Checks that the passed in QualType either is of RecordType or points
448/// to RecordType. Returns the relevant RecordType, null if it does not exit.
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000449static const RecordType *getRecordType(QualType QT) {
450 if (const RecordType *RT = QT->getAs<RecordType>())
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000451 return RT;
Benjamin Kramer56b675f2011-08-19 04:18:11 +0000452
453 // Now check if we point to record type.
454 if (const PointerType *PT = QT->getAs<PointerType>())
455 return PT->getPointeeType()->getAs<RecordType>();
456
Craig Topperc3ec1492014-05-26 06:22:03 +0000457 return nullptr;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000458}
459
Aaron Ballman76050722014-04-04 15:13:57 +0000460static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
DeLesley Hutchins481d5ab2012-04-06 20:02:30 +0000461 const RecordType *RT = getRecordType(Ty);
Michael Hana9171bc2012-08-03 17:40:43 +0000462
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000463 if (!RT)
464 return false;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000465
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000466 // Don't check for the capability if the class hasn't been defined yet.
DeLesley Hutchins3509f292012-02-16 17:15:51 +0000467 if (RT->isIncompleteType())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000468 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000469
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000470 // Allow smart pointers to be used as capability objects.
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000471 // FIXME -- Check the type that the smart pointer points to.
472 if (threadSafetyCheckIsSmartPointer(S, RT))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000473 return true;
DeLesley Hutchins90ff4682012-05-02 22:18:42 +0000474
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000475 // Check if the record itself has a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000476 RecordDecl *RD = RT->getDecl();
Aaron Ballmanefe348e2014-02-18 17:36:50 +0000477 if (RD->hasAttr<CapabilityAttr>())
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000478 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000479
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000480 // Else check if any base classes have a capability.
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000481 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
482 CXXBasePaths BPaths(false, false);
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +0000483 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
484 const auto *Type = BS->getType()->getAs<RecordType>();
485 return Type->getDecl()->hasAttr<CapabilityAttr>();
486 }, BPaths))
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000487 return true;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000488 }
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000489 return false;
490}
491
Aaron Ballman76050722014-04-04 15:13:57 +0000492static bool checkTypedefTypeForCapability(QualType Ty) {
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000493 const auto *TD = Ty->getAs<TypedefType>();
494 if (!TD)
495 return false;
496
497 TypedefNameDecl *TN = TD->getDecl();
498 if (!TN)
499 return false;
500
501 return TN->hasAttr<CapabilityAttr>();
502}
503
Aaron Ballman76050722014-04-04 15:13:57 +0000504static bool typeHasCapability(Sema &S, QualType Ty) {
505 if (checkTypedefTypeForCapability(Ty))
506 return true;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000507
Aaron Ballman76050722014-04-04 15:13:57 +0000508 if (checkRecordTypeForCapability(S, Ty))
509 return true;
DeLesley Hutchins5ff430c2012-05-04 16:28:38 +0000510
Aaron Ballman76050722014-04-04 15:13:57 +0000511 return false;
512}
513
514static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
515 // Capability expressions are simple expressions involving the boolean logic
516 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
517 // a DeclRefExpr is found, its type should be checked to determine whether it
518 // is a capability or not.
519
520 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
521 return typeHasCapability(S, E->getType());
522 else if (const auto *E = dyn_cast<CastExpr>(Ex))
523 return isCapabilityExpr(S, E->getSubExpr());
524 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
525 return isCapabilityExpr(S, E->getSubExpr());
526 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
527 if (E->getOpcode() == UO_LNot)
528 return isCapabilityExpr(S, E->getSubExpr());
529 return false;
530 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
531 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
532 return isCapabilityExpr(S, E->getLHS()) &&
533 isCapabilityExpr(S, E->getRHS());
534 return false;
535 }
536
537 return false;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000538}
539
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000540/// \brief Checks that all attribute arguments, starting from Sidx, resolve to
541/// a capability object.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000542/// \param Sidx The attribute argument index to start checking with.
543/// \param ParamIdxOk Whether an argument can be indexing into a function
544/// parameter list.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000545static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
546 const AttributeList &Attr,
547 SmallVectorImpl<Expr *> &Args,
548 int Sidx = 0,
549 bool ParamIdxOk = false) {
550 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
Aaron Ballman00e99962013-08-31 01:11:41 +0000551 Expr *ArgExp = Attr.getArgAsExpr(Idx);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000552
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000553 if (ArgExp->isTypeDependent()) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000554 // FIXME -- need to check this again on template instantiation
Caitlin Sadowski990d5712011-09-08 17:42:31 +0000555 Args.push_back(ArgExp);
556 continue;
557 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000558
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000559 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000560 if (StrLit->getLength() == 0 ||
Benjamin Kramerca9fe142013-09-13 16:30:12 +0000561 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000562 // Pass empty strings to the analyzer without warnings.
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000563 // Treat "*" as the universal lock.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000564 Args.push_back(ArgExp);
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000565 continue;
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000566 }
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000567
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000568 // We allow constant strings to be used as a placeholder for expressions
569 // that are not valid C++ syntax, but warn that they are ignored.
570 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
571 Attr.getName();
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000572 Args.push_back(ArgExp);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000573 continue;
574 }
575
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000576 QualType ArgTy = ArgExp->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000577
DeLesley Hutchins70b5e8e2012-04-23 16:45:01 +0000578 // A pointer to member expression of the form &MyClass::mu is treated
579 // specially -- we need to look at the type of the member.
580 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
581 if (UOp->getOpcode() == UO_AddrOf)
582 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
583 if (DRE->getDecl()->isCXXInstanceMember())
584 ArgTy = DRE->getDecl()->getType();
585
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000586 // First see if we can just cast to record type, or pointer to record type.
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000587 const RecordType *RT = getRecordType(ArgTy);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000588
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000589 // Now check if we index into a record type function param.
590 if(!RT && ParamIdxOk) {
591 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000592 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
593 if(FD && IL) {
594 unsigned int NumParams = FD->getNumParams();
595 llvm::APInt ArgValue = IL->getValue();
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000596 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
597 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
598 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000599 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
600 << Attr.getName() << Idx + 1 << NumParams;
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000601 continue;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000602 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000603 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000604 }
605 }
606
Aaron Ballman76050722014-04-04 15:13:57 +0000607 // If the type does not have a capability, see if the components of the
608 // expression have capabilities. This allows for writing C code where the
609 // capability may be on the type, and the expression is a capability
610 // boolean logic expression. Eg) requires_capability(A || B && !C)
611 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
612 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
613 << Attr.getName() << ArgTy;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000614
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000615 Args.push_back(ArgExp);
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000616 }
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000617}
618
Chris Lattner58418ff2008-06-29 00:16:31 +0000619//===----------------------------------------------------------------------===//
Chris Lattner58418ff2008-06-29 00:16:31 +0000620// Attribute Implementations
621//===----------------------------------------------------------------------===//
622
Michael Hana9171bc2012-08-03 17:40:43 +0000623static void handlePtGuardedVarAttr(Sema &S, Decl *D,
Michael Han99315932013-01-24 16:46:58 +0000624 const AttributeList &Attr) {
Michael Han3be3b442012-07-23 18:48:41 +0000625 if (!threadSafetyCheckIsPointer(S, D, Attr))
626 return;
627
Michael Han99315932013-01-24 16:46:58 +0000628 D->addAttr(::new (S.Context)
629 PtGuardedVarAttr(Attr.getRange(), S.Context,
630 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000631}
632
Michael Hana9171bc2012-08-03 17:40:43 +0000633static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
634 const AttributeList &Attr,
Michael Han3be3b442012-07-23 18:48:41 +0000635 Expr* &Arg) {
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000636 SmallVector<Expr*, 1> Args;
637 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000638 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000639 unsigned Size = Args.size();
640 if (Size != 1)
Michael Han3be3b442012-07-23 18:48:41 +0000641 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000642
Michael Han3be3b442012-07-23 18:48:41 +0000643 Arg = Args[0];
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000644
Michael Han3be3b442012-07-23 18:48:41 +0000645 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000646}
647
Michael Han3be3b442012-07-23 18:48:41 +0000648static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000649 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000650 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
651 return;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000652
Aaron Ballman36a53502014-01-16 13:03:14 +0000653 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
654 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000655}
656
Michael Hana9171bc2012-08-03 17:40:43 +0000657static void handlePtGuardedByAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000658 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000659 Expr *Arg = nullptr;
Michael Han3be3b442012-07-23 18:48:41 +0000660 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
661 return;
662
663 if (!threadSafetyCheckIsPointer(S, D, Attr))
664 return;
665
666 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +0000667 S.Context, Arg,
668 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000669}
670
Michael Hana9171bc2012-08-03 17:40:43 +0000671static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
672 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000673 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000674 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000675 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000676
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000677 // Check that this attribute only applies to lockable types.
Aaron Ballmane61b8b82013-12-02 15:02:49 +0000678 QualType QT = cast<ValueDecl>(D)->getType();
DeLesley Hutchins2b504dc2015-09-29 16:24:18 +0000679 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
680 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
681 << Attr.getName();
682 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000683 }
684
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000685 // Check that all arguments are lockable objects.
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000686 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000687 if (Args.empty())
Michael Han3be3b442012-07-23 18:48:41 +0000688 return false;
Michael Hana9171bc2012-08-03 17:40:43 +0000689
Michael Han3be3b442012-07-23 18:48:41 +0000690 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000691}
692
Michael Hana9171bc2012-08-03 17:40:43 +0000693static void handleAcquiredAfterAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000694 const AttributeList &Attr) {
695 SmallVector<Expr*, 1> Args;
696 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
697 return;
698
699 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000700 D->addAttr(::new (S.Context)
701 AcquiredAfterAttr(Attr.getRange(), S.Context,
702 StartArg, Args.size(),
703 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000704}
705
Michael Hana9171bc2012-08-03 17:40:43 +0000706static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000707 const AttributeList &Attr) {
708 SmallVector<Expr*, 1> Args;
709 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
710 return;
711
712 Expr **StartArg = &Args[0];
Michael Han99315932013-01-24 16:46:58 +0000713 D->addAttr(::new (S.Context)
714 AcquiredBeforeAttr(Attr.getRange(), S.Context,
715 StartArg, Args.size(),
716 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000717}
718
Michael Hana9171bc2012-08-03 17:40:43 +0000719static bool checkLockFunAttrCommon(Sema &S, Decl *D,
720 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000721 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000722 // zero or more arguments ok
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000723 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000724 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000725
Michael Han3be3b442012-07-23 18:48:41 +0000726 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000727}
728
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000729static void handleAssertSharedLockAttr(Sema &S, Decl *D,
730 const AttributeList &Attr) {
731 SmallVector<Expr*, 1> Args;
732 if (!checkLockFunAttrCommon(S, D, Attr, Args))
733 return;
734
735 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000736 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000737 D->addAttr(::new (S.Context)
738 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
739 Attr.getAttributeSpellingListIndex()));
740}
741
742static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
743 const AttributeList &Attr) {
744 SmallVector<Expr*, 1> Args;
745 if (!checkLockFunAttrCommon(S, D, Attr, Args))
746 return;
747
748 unsigned Size = Args.size();
Craig Topperc3ec1492014-05-26 06:22:03 +0000749 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000750 D->addAttr(::new (S.Context)
751 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
752 StartArg, Size,
753 Attr.getAttributeSpellingListIndex()));
754}
755
George Burgess IVe3763372016-12-22 02:50:20 +0000756/// \brief Checks to be sure that the given parameter number is inbounds, and is
757/// an some integral type. Will emit appropriate diagnostics if this returns
758/// false.
759///
760/// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
761/// to actually retrieve the argument, so it's base-0.
762static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
763 const AttributeList &Attr,
764 unsigned FuncParamNo, unsigned AttrArgNo) {
765 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
766 uint64_t Idx;
767 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo,
768 Attr.getArgAsExpr(AttrArgNo), Idx))
769 return false;
770
771 const ParmVarDecl *Param = FD->getParamDecl(Idx);
772 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
773 SourceLocation SrcLoc = Attr.getArgAsExpr(AttrArgNo)->getLocStart();
774 S.Diag(SrcLoc, diag::err_attribute_integers_only)
775 << Attr.getName() << Param->getSourceRange();
776 return false;
777 }
778 return true;
779}
780
781static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
782 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
783 !checkAttributeAtMostNumArgs(S, Attr, 2))
784 return;
785
786 const auto *FD = cast<FunctionDecl>(D);
787 if (!FD->getReturnType()->isPointerType()) {
788 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
789 << Attr.getName();
790 return;
791 }
792
793 const Expr *SizeExpr = Attr.getArgAsExpr(0);
794 int SizeArgNo;
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000795 // Parameter indices are 1-indexed, hence Index=1
George Burgess IVe3763372016-12-22 02:50:20 +0000796 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
797 return;
798
799 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
800 return;
801
802 // Args are 1-indexed, so 0 implies that the arg was not present
803 int NumberArgNo = 0;
804 if (Attr.getNumArgs() == 2) {
805 const Expr *NumberExpr = Attr.getArgAsExpr(1);
Simon Pilgrim27cc0542017-02-15 15:12:06 +0000806 // Parameter indices are 1-based, hence Index=2
George Burgess IVe3763372016-12-22 02:50:20 +0000807 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
808 /*Index=*/2))
809 return;
810
811 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
812 return;
813 }
814
815 D->addAttr(::new (S.Context) AllocSizeAttr(
816 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
817 Attr.getAttributeSpellingListIndex()));
818}
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000819
Michael Hana9171bc2012-08-03 17:40:43 +0000820static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
821 const AttributeList &Attr,
Craig Topper5603df42013-07-05 19:34:19 +0000822 SmallVectorImpl<Expr *> &Args) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000823 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Michael Han3be3b442012-07-23 18:48:41 +0000824 return false;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000825
Aaron Ballman00e99962013-08-31 01:11:41 +0000826 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
Aaron Ballman29982272013-07-23 14:03:57 +0000827 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +0000828 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
Michael Han3be3b442012-07-23 18:48:41 +0000829 return false;
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000830 }
831
832 // check that all arguments are lockable objects
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000833 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000834
Michael Han3be3b442012-07-23 18:48:41 +0000835 return true;
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000836}
837
Michael Hana9171bc2012-08-03 17:40:43 +0000838static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000839 const AttributeList &Attr) {
840 SmallVector<Expr*, 2> Args;
841 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
842 return;
843
Michael Han99315932013-01-24 16:46:58 +0000844 D->addAttr(::new (S.Context)
845 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
Aaron Ballman00e99962013-08-31 01:11:41 +0000846 Attr.getArgAsExpr(0),
847 Args.data(), Args.size(),
Michael Han99315932013-01-24 16:46:58 +0000848 Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000849}
850
Michael Hana9171bc2012-08-03 17:40:43 +0000851static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
Michael Han3be3b442012-07-23 18:48:41 +0000852 const AttributeList &Attr) {
853 SmallVector<Expr*, 2> Args;
854 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
855 return;
856
Nico Weber462fd1e2015-01-07 23:50:05 +0000857 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
858 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
859 Args.size(), Attr.getAttributeSpellingListIndex()));
Michael Han3be3b442012-07-23 18:48:41 +0000860}
861
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000862static void handleLockReturnedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000863 const AttributeList &Attr) {
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000864 // check that the argument is lockable object
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000865 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000866 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
DeLesley Hutchinsd96b46a2012-05-02 17:38:37 +0000867 unsigned Size = Args.size();
868 if (Size == 0)
869 return;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000870
Michael Han99315932013-01-24 16:46:58 +0000871 D->addAttr(::new (S.Context)
872 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
873 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000874}
875
876static void handleLocksExcludedAttr(Sema &S, Decl *D,
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000877 const AttributeList &Attr) {
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000878 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000879 return;
880
Caitlin Sadowski4b1e8392011-08-09 17:59:31 +0000881 // check that all arguments are lockable objects
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000882 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +0000883 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000884 unsigned Size = Args.size();
DeLesley Hutchins8d11c792012-04-19 16:10:44 +0000885 if (Size == 0)
886 return;
887 Expr **StartArg = &Args[0];
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +0000888
Michael Han99315932013-01-24 16:46:58 +0000889 D->addAttr(::new (S.Context)
890 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
891 Attr.getAttributeSpellingListIndex()));
Caitlin Sadowski63fa6672011-07-28 20:12:35 +0000892}
893
George Burgess IV177399e2017-01-09 04:12:14 +0000894static bool checkFunctionConditionAttr(Sema &S, Decl *D,
895 const AttributeList &Attr,
896 Expr *&Cond, StringRef &Msg) {
897 Cond = Attr.getArgAsExpr(0);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000898 if (!Cond->isTypeDependent()) {
899 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
900 if (Converted.isInvalid())
George Burgess IV177399e2017-01-09 04:12:14 +0000901 return false;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000902 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000903 }
904
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000905 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
George Burgess IV177399e2017-01-09 04:12:14 +0000906 return false;
907
908 if (Msg.empty())
909 Msg = "<no message provided>";
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000910
911 SmallVector<PartialDiagnosticAt, 8> Diags;
912 if (!Cond->isValueDependent() &&
913 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
914 Diags)) {
George Burgess IV177399e2017-01-09 04:12:14 +0000915 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
916 << Attr.getName();
George Burgess IV0d546532016-11-10 21:47:12 +0000917 for (const PartialDiagnosticAt &PDiag : Diags)
918 S.Diag(PDiag.first, PDiag.second);
George Burgess IV177399e2017-01-09 04:12:14 +0000919 return false;
920 }
921 return true;
922}
923
924static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
925 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
926
927 Expr *Cond;
928 StringRef Msg;
929 if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
930 D->addAttr(::new (S.Context)
931 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
932 Attr.getAttributeSpellingListIndex()));
933}
934
935namespace {
936/// Determines if a given Expr references any of the given function's
937/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
938class ArgumentDependenceChecker
939 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
940#ifndef NDEBUG
941 const CXXRecordDecl *ClassType;
942#endif
943 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
944 bool Result;
945
946public:
947 ArgumentDependenceChecker(const FunctionDecl *FD) {
948#ifndef NDEBUG
949 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
950 ClassType = MD->getParent();
951 else
952 ClassType = nullptr;
953#endif
954 Parms.insert(FD->param_begin(), FD->param_end());
955 }
956
957 bool referencesArgs(Expr *E) {
958 Result = false;
959 TraverseStmt(E);
960 return Result;
961 }
962
963 bool VisitCXXThisExpr(CXXThisExpr *E) {
964 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
965 "`this` doesn't refer to the enclosing class?");
966 Result = true;
967 return false;
968 }
969
970 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
971 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
972 if (Parms.count(PVD)) {
973 Result = true;
974 return false;
975 }
976 return true;
977 }
978};
979}
980
981static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
982 S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if);
983
984 Expr *Cond;
985 StringRef Msg;
986 if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
987 return;
988
989 StringRef DiagTypeStr;
990 if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr))
991 return;
992
993 DiagnoseIfAttr::DiagnosticType DiagType;
994 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
995 S.Diag(Attr.getArgAsExpr(2)->getLocStart(),
996 diag::err_diagnose_if_invalid_diagnostic_type);
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000997 return;
998 }
999
George Burgess IV177399e2017-01-09 04:12:14 +00001000 auto *FD = cast<FunctionDecl>(D);
1001 bool ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1002 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1003 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, FD,
1004 Attr.getAttributeSpellingListIndex()));
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001005}
1006
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001007static void handlePassObjectSizeAttr(Sema &S, Decl *D,
1008 const AttributeList &Attr) {
1009 if (D->hasAttr<PassObjectSizeAttr>()) {
1010 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1011 << Attr.getName();
1012 return;
1013 }
1014
1015 Expr *E = Attr.getArgAsExpr(0);
1016 uint32_t Type;
1017 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
1018 return;
1019
1020 // pass_object_size's argument is passed in as the second argument of
1021 // __builtin_object_size. So, it has the same constraints as that second
1022 // argument; namely, it must be in the range [0, 3].
1023 if (Type > 3) {
1024 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1025 << Attr.getName() << 0 << 3 << E->getSourceRange();
1026 return;
1027 }
1028
1029 // pass_object_size is only supported on constant pointer parameters; as a
1030 // kindness to users, we allow the parameter to be non-const for declarations.
1031 // At this point, we have no clue if `D` belongs to a function declaration or
1032 // definition, so we defer the constness check until later.
1033 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1034 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1035 << Attr.getName() << 1;
1036 return;
1037 }
1038
1039 D->addAttr(::new (S.Context)
1040 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
1041 Attr.getAttributeSpellingListIndex()));
1042}
1043
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001044static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
David Blaikie16f76d22013-09-06 01:28:43 +00001045 ConsumableAttr::ConsumedState DefaultState;
1046
1047 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001048 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1049 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1050 DefaultState)) {
1051 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1052 << Attr.getName() << IL->Ident;
David Blaikie16f76d22013-09-06 01:28:43 +00001053 return;
1054 }
David Blaikie16f76d22013-09-06 01:28:43 +00001055 } else {
1056 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1057 << Attr.getName() << AANT_ArgumentIdentifier;
1058 return;
1059 }
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001060
1061 D->addAttr(::new (S.Context)
David Blaikie16f76d22013-09-06 01:28:43 +00001062 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001063 Attr.getAttributeSpellingListIndex()));
1064}
1065
1066static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1067 const AttributeList &Attr) {
1068 ASTContext &CurrContext = S.getASTContext();
1069 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1070
1071 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1072 if (!RD->hasAttr<ConsumableAttr>()) {
1073 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1074 RD->getNameAsString();
1075
1076 return false;
1077 }
1078 }
1079
1080 return true;
1081}
1082
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001083static void handleCallableWhenAttr(Sema &S, Decl *D,
1084 const AttributeList &Attr) {
Aaron Ballmandbd586f2013-10-14 23:26:04 +00001085 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1086 return;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001087
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00001088 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1089 return;
1090
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001091 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1092 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1093 CallableWhenAttr::ConsumedState CallableState;
1094
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001095 StringRef StateString;
1096 SourceLocation Loc;
Aaron Ballman55ef1512014-12-19 16:42:04 +00001097 if (Attr.isArgIdent(ArgIndex)) {
1098 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1099 StateString = Ident->Ident->getName();
1100 Loc = Ident->Loc;
1101 } else {
1102 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1103 return;
1104 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001105
1106 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
DeLesley Hutchins69391772013-10-17 23:23:53 +00001107 CallableState)) {
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001108 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1109 << Attr.getName() << StateString;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001110 return;
1111 }
Aaron Ballman4c9b7dc2013-10-05 22:45:34 +00001112
1113 States.push_back(CallableState);
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001114 }
1115
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001116 D->addAttr(::new (S.Context)
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001117 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1118 States.size(), Attr.getAttributeSpellingListIndex()));
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001119}
1120
DeLesley Hutchins69391772013-10-17 23:23:53 +00001121static void handleParamTypestateAttr(Sema &S, Decl *D,
1122 const AttributeList &Attr) {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001123 ParamTypestateAttr::ConsumedState ParamState;
1124
1125 if (Attr.isArgIdent(0)) {
1126 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1127 StringRef StateString = Ident->Ident->getName();
1128
1129 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1130 ParamState)) {
1131 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1132 << Attr.getName() << StateString;
1133 return;
1134 }
1135 } else {
1136 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1137 Attr.getName() << AANT_ArgumentIdentifier;
1138 return;
1139 }
1140
1141 // FIXME: This check is currently being done in the analysis. It can be
1142 // enabled here only after the parser propagates attributes at
1143 // template specialization definition, not declaration.
1144 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1145 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1146 //
1147 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1148 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1149 // ReturnType.getAsString();
1150 // return;
1151 //}
1152
1153 D->addAttr(::new (S.Context)
1154 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1155 Attr.getAttributeSpellingListIndex()));
1156}
1157
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001158static void handleReturnTypestateAttr(Sema &S, Decl *D,
1159 const AttributeList &Attr) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001160 ReturnTypestateAttr::ConsumedState ReturnState;
1161
1162 if (Attr.isArgIdent(0)) {
Aaron Ballman682ee422013-09-11 19:47:58 +00001163 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1164 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1165 ReturnState)) {
1166 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1167 << Attr.getName() << IL->Ident;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001168 return;
1169 }
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001170 } else {
1171 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1172 Attr.getName() << AANT_ArgumentIdentifier;
1173 return;
1174 }
1175
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001176 // FIXME: This check is currently being done in the analysis. It can be
1177 // enabled here only after the parser propagates attributes at
1178 // template specialization definition, not declaration.
1179 //QualType ReturnType;
1180 //
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001181 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1182 // ReturnType = Param->getType();
1183 //
1184 //} else if (const CXXConstructorDecl *Constructor =
1185 // dyn_cast<CXXConstructorDecl>(D)) {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001186 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1187 //
1188 //} else {
1189 //
1190 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1191 //}
1192 //
1193 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1194 //
1195 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1196 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1197 // ReturnType.getAsString();
1198 // return;
1199 //}
1200
1201 D->addAttr(::new (S.Context)
1202 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1203 Attr.getAttributeSpellingListIndex()));
1204}
1205
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001206static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001207 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1208 return;
1209
1210 SetTypestateAttr::ConsumedState NewState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001211 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001212 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1213 StringRef Param = Ident->Ident->getName();
1214 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1215 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1216 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001217 return;
1218 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001219 } else {
1220 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1221 Attr.getName() << AANT_ArgumentIdentifier;
1222 return;
1223 }
1224
1225 D->addAttr(::new (S.Context)
1226 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1227 Attr.getAttributeSpellingListIndex()));
1228}
1229
Chris Wailes9385f9f2013-10-29 20:28:41 +00001230static void handleTestTypestateAttr(Sema &S, Decl *D,
1231 const AttributeList &Attr) {
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001232 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1233 return;
1234
Chris Wailes9385f9f2013-10-29 20:28:41 +00001235 TestTypestateAttr::ConsumedState TestState;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001236 if (Attr.isArgIdent(0)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001237 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1238 StringRef Param = Ident->Ident->getName();
Chris Wailes9385f9f2013-10-29 20:28:41 +00001239 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
Aaron Ballman91c98e12013-10-14 23:22:37 +00001240 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1241 << Attr.getName() << Param;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001242 return;
1243 }
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001244 } else {
1245 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1246 Attr.getName() << AANT_ArgumentIdentifier;
1247 return;
1248 }
1249
1250 D->addAttr(::new (S.Context)
Chris Wailes9385f9f2013-10-29 20:28:41 +00001251 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
DeLesley Hutchins33a29342013-10-11 23:03:26 +00001252 Attr.getAttributeSpellingListIndex()));
1253}
1254
Chandler Carruthedc2c642011-07-02 00:01:44 +00001255static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1256 const AttributeList &Attr) {
Richard Smith1f5a4322013-01-13 02:11:23 +00001257 // Remember this typedef decl, we will need it later for diagnostics.
Aaron Ballman74eeeae2013-11-27 13:27:02 +00001258 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001259}
1260
Chandler Carruthedc2c642011-07-02 00:01:44 +00001261static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001262 if (TagDecl *TD = dyn_cast<TagDecl>(D))
Aaron Ballman36a53502014-01-16 13:03:14 +00001263 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1264 Attr.getAttributeSpellingListIndex()));
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001265 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001266 // Report warning about changed offset in the newer compiler versions.
Eli Friedmanc087c3f2012-11-07 00:35:20 +00001267 if (!FD->getType()->isDependentType() &&
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001268 !FD->getType()->isIncompleteType() && FD->isBitField() &&
Chris Lattnerb632a6e2008-06-29 00:43:07 +00001269 S.Context.getTypeAlign(FD->getType()) <= 8)
Alexey Bataev830dfcc2015-12-03 09:34:49 +00001270 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1271
1272 FD->addAttr(::new (S.Context) PackedAttr(
1273 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001274 } else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001275 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001276}
1277
Ted Kremenek7fd17232011-09-29 07:02:25 +00001278static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1279 // The IBOutlet/IBOutletCollection attributes only apply to instance
1280 // variables or properties of Objective-C classes. The outlet must also
1281 // have an object reference type.
1282 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1283 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
Ted Kremenek5d6044e2011-11-01 18:08:35 +00001284 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001285 << Attr.getName() << VD->getType() << 0;
1286 return false;
1287 }
1288 }
1289 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1290 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001291 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
Ted Kremenek7fd17232011-09-29 07:02:25 +00001292 << Attr.getName() << PD->getType() << 1;
1293 return false;
1294 }
1295 }
1296 else {
1297 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1298 return false;
1299 }
Douglas Gregor5c3cc422012-03-14 16:55:17 +00001300
Ted Kremenek7fd17232011-09-29 07:02:25 +00001301 return true;
1302}
1303
Chandler Carruthedc2c642011-07-02 00:01:44 +00001304static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
Ted Kremenek7fd17232011-09-29 07:02:25 +00001305 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek1f672822010-02-18 03:08:58 +00001306 return;
Ted Kremenek1f672822010-02-18 03:08:58 +00001307
Michael Han99315932013-01-24 16:46:58 +00001308 D->addAttr(::new (S.Context)
1309 IBOutletAttr(Attr.getRange(), S.Context,
1310 Attr.getAttributeSpellingListIndex()));
Ted Kremenek8e3704d2008-07-15 22:26:48 +00001311}
1312
Chandler Carruthedc2c642011-07-02 00:01:44 +00001313static void handleIBOutletCollection(Sema &S, Decl *D,
1314 const AttributeList &Attr) {
Ted Kremenek26bde772010-05-19 17:38:06 +00001315
1316 // The iboutletcollection attribute can have zero or one arguments.
Aaron Ballman00e99962013-08-31 01:11:41 +00001317 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001318 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1319 << Attr.getName() << 1;
Ted Kremenek26bde772010-05-19 17:38:06 +00001320 return;
1321 }
1322
Ted Kremenek7fd17232011-09-29 07:02:25 +00001323 if (!checkIBOutletCommon(S, D, Attr))
Ted Kremenek26bde772010-05-19 17:38:06 +00001324 return;
Ted Kremenek7fd17232011-09-29 07:02:25 +00001325
Richard Smithb1f9a282013-10-31 01:56:18 +00001326 ParsedType PT;
1327
1328 if (Attr.hasParsedType())
1329 PT = Attr.getTypeArg();
1330 else {
1331 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1332 S.getScopeForContext(D->getDeclContext()->getParent()));
1333 if (!PT) {
1334 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1335 return;
1336 }
Aaron Ballman00e99962013-08-31 01:11:41 +00001337 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001338
Craig Topperc3ec1492014-05-26 06:22:03 +00001339 TypeSourceInfo *QTLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00001340 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1341 if (!QTLoc)
1342 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
Richard Smithb1f9a282013-10-31 01:56:18 +00001343
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001344 // Diagnose use of non-object type in iboutletcollection attribute.
1345 // FIXME. Gnu attribute extension ignores use of builtin types in
1346 // attributes. So, __attribute__((iboutletcollection(char))) will be
1347 // treated as __attribute__((iboutletcollection())).
Fariborz Jahanian2f31b332011-10-18 19:54:31 +00001348 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
Richard Smithb1f9a282013-10-31 01:56:18 +00001349 S.Diag(Attr.getLoc(),
1350 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1351 : diag::err_iboutletcollection_type) << QT;
Fariborz Jahanianb5d59b62010-08-17 20:23:12 +00001352 return;
1353 }
Richard Smithb1f9a282013-10-31 01:56:18 +00001354
Michael Han99315932013-01-24 16:46:58 +00001355 D->addAttr(::new (S.Context)
Richard Smithb87c4652013-10-31 21:23:20 +00001356 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
Michael Han99315932013-01-24 16:46:58 +00001357 Attr.getAttributeSpellingListIndex()));
Ted Kremenek26bde772010-05-19 17:38:06 +00001358}
1359
Hal Finkelee90a222014-09-26 05:04:30 +00001360bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1361 if (RefOkay) {
1362 if (T->isReferenceType())
1363 return true;
1364 } else {
1365 T = T.getNonReferenceType();
1366 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001367
Hal Finkelee90a222014-09-26 05:04:30 +00001368 // The nonnull attribute, and other similar attributes, can be applied to a
1369 // transparent union that contains a pointer type.
Richard Smith588bd9b2014-08-27 04:59:42 +00001370 if (const RecordType *UT = T->getAsUnionType()) {
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001371 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1372 RecordDecl *UD = UT->getDecl();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001373 for (const auto *I : UD->fields()) {
1374 QualType QT = I->getType();
Richard Smith588bd9b2014-08-27 04:59:42 +00001375 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1376 return true;
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001377 }
1378 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001379 }
1380
1381 return T->isAnyPointerType() || T->isBlockPointerType();
Fariborz Jahanianf4aa2792011-06-27 21:12:03 +00001382}
1383
Ted Kremenek9aedc152014-01-17 06:24:56 +00001384static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001385 SourceRange AttrParmRange,
Hal Finkelee90a222014-09-26 05:04:30 +00001386 SourceRange TypeRange,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001387 bool isReturnValue = false) {
Hal Finkelee90a222014-09-26 05:04:30 +00001388 if (!S.isValidPointerAttrType(T)) {
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001389 if (isReturnValue)
1390 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1391 << Attr.getName() << AttrParmRange << TypeRange;
1392 else
1393 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1394 << Attr.getName() << AttrParmRange << TypeRange << 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001395 return false;
1396 }
1397 return true;
1398}
1399
Chandler Carruthedc2c642011-07-02 00:01:44 +00001400static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001401 SmallVector<unsigned, 8> NonNullArgs;
Richard Smith588bd9b2014-08-27 04:59:42 +00001402 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1403 Expr *Ex = Attr.getArgAsExpr(I);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001404 uint64_t Idx;
Richard Smith588bd9b2014-08-27 04:59:42 +00001405 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001406 return;
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001407
1408 // Is the function argument a pointer type?
Richard Smith588bd9b2014-08-27 04:59:42 +00001409 if (Idx < getFunctionOrMethodNumParams(D) &&
1410 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001411 Ex->getSourceRange(),
1412 getFunctionOrMethodParamRange(D, Idx)))
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001413 continue;
Mike Stumpd3bb5572009-07-24 19:02:52 +00001414
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001415 NonNullArgs.push_back(Idx);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001416 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001417
1418 // If no arguments were specified to __attribute__((nonnull)) then all pointer
Richard Smith588bd9b2014-08-27 04:59:42 +00001419 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1420 // check if the attribute came from a macro expansion or a template
1421 // instantiation.
1422 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001423 !S.inTemplateInstantiation()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001424 bool AnyPointers = isFunctionOrMethodVariadic(D);
1425 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1426 I != E && !AnyPointers; ++I) {
1427 QualType T = getFunctionOrMethodParamType(D, I);
Hal Finkelee90a222014-09-26 05:04:30 +00001428 if (T->isDependentType() || S.isValidPointerAttrType(T))
Richard Smith588bd9b2014-08-27 04:59:42 +00001429 AnyPointers = true;
Ted Kremenek5fa50522008-11-18 06:52:58 +00001430 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001431
Richard Smith588bd9b2014-08-27 04:59:42 +00001432 if (!AnyPointers)
1433 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001434 }
Ted Kremenekc4f6d902008-09-01 19:57:52 +00001435
Richard Smith588bd9b2014-08-27 04:59:42 +00001436 unsigned *Start = NonNullArgs.data();
1437 unsigned Size = NonNullArgs.size();
1438 llvm::array_pod_sort(Start, Start + Size);
Michael Han99315932013-01-24 16:46:58 +00001439 D->addAttr(::new (S.Context)
Richard Smith588bd9b2014-08-27 04:59:42 +00001440 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
Michael Han99315932013-01-24 16:46:58 +00001441 Attr.getAttributeSpellingListIndex()));
Ted Kremenek2d63bc12008-07-21 21:53:04 +00001442}
1443
Jordan Rosec9399072014-02-11 17:27:59 +00001444static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1445 const AttributeList &Attr) {
1446 if (Attr.getNumArgs() > 0) {
1447 if (D->getFunctionType()) {
1448 handleNonNullAttr(S, D, Attr);
1449 } else {
1450 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1451 << D->getSourceRange();
1452 }
1453 return;
1454 }
1455
1456 // Is the argument a pointer type?
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001457 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1458 D->getSourceRange()))
Jordan Rosec9399072014-02-11 17:27:59 +00001459 return;
1460
1461 D->addAttr(::new (S.Context)
Craig Topperc3ec1492014-05-26 06:22:03 +00001462 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
Jordan Rosec9399072014-02-11 17:27:59 +00001463 Attr.getAttributeSpellingListIndex()));
1464}
1465
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001466static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1467 const AttributeList &Attr) {
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00001468 QualType ResultType = getFunctionOrMethodResultType(D);
Aaron Ballman4bfa0de2014-08-01 12:58:11 +00001469 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1470 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
Ted Kremenekdbf62e32014-01-20 05:50:47 +00001471 /* isReturnValue */ true))
1472 return;
1473
1474 D->addAttr(::new (S.Context)
1475 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1476 Attr.getAttributeSpellingListIndex()));
1477}
1478
Hal Finkelee90a222014-09-26 05:04:30 +00001479static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1480 const AttributeList &Attr) {
1481 Expr *E = Attr.getArgAsExpr(0),
1482 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1483 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1484 Attr.getAttributeSpellingListIndex());
1485}
1486
1487void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1488 Expr *OE, unsigned SpellingListIndex) {
1489 QualType ResultType = getFunctionOrMethodResultType(D);
1490 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1491
1492 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1493 SourceLocation AttrLoc = AttrRange.getBegin();
1494
1495 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1496 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1497 << &TmpAttr << AttrRange << SR;
1498 return;
1499 }
1500
1501 if (!E->isValueDependent()) {
1502 llvm::APSInt I(64);
1503 if (!E->isIntegerConstantExpr(I, Context)) {
1504 if (OE)
1505 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1506 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1507 << E->getSourceRange();
1508 else
1509 Diag(AttrLoc, diag::err_attribute_argument_type)
1510 << &TmpAttr << AANT_ArgumentIntegerConstant
1511 << E->getSourceRange();
1512 return;
1513 }
1514
1515 if (!I.isPowerOf2()) {
1516 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1517 << E->getSourceRange();
1518 return;
1519 }
1520 }
1521
1522 if (OE) {
1523 if (!OE->isValueDependent()) {
1524 llvm::APSInt I(64);
1525 if (!OE->isIntegerConstantExpr(I, Context)) {
1526 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1527 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1528 << OE->getSourceRange();
1529 return;
1530 }
1531 }
1532 }
1533
1534 D->addAttr(::new (Context)
1535 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1536}
1537
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001538/// Normalize the attribute, __foo__ becomes foo.
1539/// Returns true if normalization was applied.
1540static bool normalizeName(StringRef &AttrName) {
Aaron Ballman62692362015-10-09 13:53:24 +00001541 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1542 AttrName.endswith("__")) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001543 AttrName = AttrName.drop_front(2).drop_back(2);
1544 return true;
1545 }
1546 return false;
1547}
1548
Chandler Carruthedc2c642011-07-02 00:01:44 +00001549static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001550 // This attribute must be applied to a function declaration. The first
1551 // argument to the attribute must be an identifier, the name of the resource,
1552 // for example: malloc. The following arguments must be argument indexes, the
1553 // arguments must be of integer type for Returns, otherwise of pointer type.
Ted Kremenekd21139a2010-07-31 01:52:11 +00001554 // The difference between Holds and Takes is that a pointer may still be used
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001555 // after being held. free() should be __attribute((ownership_takes)), whereas
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001556 // a list append function may well be __attribute((ownership_holds)).
Ted Kremenekd21139a2010-07-31 01:52:11 +00001557
Aaron Ballman00e99962013-08-31 01:11:41 +00001558 if (!AL.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00001559 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001560 << AL.getName() << 1 << AANT_ArgumentIdentifier;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001561 return;
1562 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001563
Richard Smith852e9ce2013-11-27 01:46:48 +00001564 // Figure out our Kind.
1565 OwnershipAttr::OwnershipKind K =
Craig Topperc3ec1492014-05-26 06:22:03 +00001566 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
Richard Smith852e9ce2013-11-27 01:46:48 +00001567 AL.getAttributeSpellingListIndex()).getOwnKind();
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001568
Richard Smith852e9ce2013-11-27 01:46:48 +00001569 // Check arguments.
1570 switch (K) {
1571 case OwnershipAttr::Takes:
1572 case OwnershipAttr::Holds:
1573 if (AL.getNumArgs() < 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001574 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1575 << AL.getName() << 2;
Richard Smith852e9ce2013-11-27 01:46:48 +00001576 return;
1577 }
1578 break;
1579 case OwnershipAttr::Returns:
Aaron Ballman00e99962013-08-31 01:11:41 +00001580 if (AL.getNumArgs() > 2) {
Aaron Ballman05e420a2014-01-02 21:26:14 +00001581 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1582 << AL.getName() << 1;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001583 return;
1584 }
Jordy Rose5af0e3c2010-08-12 08:54:03 +00001585 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001586 }
1587
Richard Smith852e9ce2013-11-27 01:46:48 +00001588 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001589
Richard Smith852e9ce2013-11-27 01:46:48 +00001590 StringRef ModuleName = Module->getName();
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00001591 if (normalizeName(ModuleName)) {
Richard Smith852e9ce2013-11-27 01:46:48 +00001592 Module = &S.PP.getIdentifierTable().get(ModuleName);
1593 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001594
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001595 SmallVector<unsigned, 8> OwnershipArgs;
Aaron Ballman00e99962013-08-31 01:11:41 +00001596 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1597 Expr *Ex = AL.getArgAsExpr(i);
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001598 uint64_t Idx;
Alp Toker601b22c2014-01-21 23:35:24 +00001599 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001600 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00001601
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001602 // Is the function argument a pointer type?
Alp Toker601b22c2014-01-21 23:35:24 +00001603 QualType T = getFunctionOrMethodParamType(D, Idx);
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001604 int Err = -1; // No error
Ted Kremenekd21139a2010-07-31 01:52:11 +00001605 switch (K) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001606 case OwnershipAttr::Takes:
1607 case OwnershipAttr::Holds:
1608 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1609 Err = 0;
1610 break;
1611 case OwnershipAttr::Returns:
1612 if (!T->isIntegerType())
1613 Err = 1;
1614 break;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001615 }
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001616 if (-1 != Err) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00001617 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001618 << Ex->getSourceRange();
1619 return;
Ted Kremenekd21139a2010-07-31 01:52:11 +00001620 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001621
1622 // Check we don't have a conflict with another ownership attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001623 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001624 // Cannot have two ownership attributes of different kinds for the same
1625 // index.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001626 if (I->getOwnKind() != K && I->args_end() !=
1627 std::find(I->args_begin(), I->args_end(), Idx)) {
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001628 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001629 << AL.getName() << I;
Aaron Ballman6e2dd7b2013-09-16 18:11:41 +00001630 return;
Aaron Ballmanef7aef82014-07-31 20:44:26 +00001631 } else if (K == OwnershipAttr::Returns &&
1632 I->getOwnKind() == OwnershipAttr::Returns) {
1633 // A returns attribute conflicts with any other returns attribute using
1634 // a different index. Note, diagnostic reporting is 1-based, but stored
1635 // argument indexes are 0-based.
1636 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1637 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1638 << *(I->args_begin()) + 1;
1639 if (I->args_size())
1640 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1641 << (unsigned)Idx + 1 << Ex->getSourceRange();
1642 return;
1643 }
Ted Kremenekd21139a2010-07-31 01:52:11 +00001644 }
1645 }
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00001646 OwnershipArgs.push_back(Idx);
Ted Kremenekd21139a2010-07-31 01:52:11 +00001647 }
1648
1649 unsigned* start = OwnershipArgs.data();
1650 unsigned size = OwnershipArgs.size();
1651 llvm::array_pod_sort(start, start + size);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001652
Michael Han99315932013-01-24 16:46:58 +00001653 D->addAttr(::new (S.Context)
Richard Smith852e9ce2013-11-27 01:46:48 +00001654 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
Michael Han99315932013-01-24 16:46:58 +00001655 AL.getAttributeSpellingListIndex()));
Ted Kremenekd21139a2010-07-31 01:52:11 +00001656}
1657
Chandler Carruthedc2c642011-07-02 00:01:44 +00001658static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Rafael Espindolac18086a2010-02-23 22:00:30 +00001659 // Check the attribute arguments.
1660 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00001661 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1662 << Attr.getName() << 1;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001663 return;
1664 }
1665
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001666 NamedDecl *nd = cast<NamedDecl>(D);
John McCall7a198ce2011-02-08 22:35:49 +00001667
Rafael Espindolac18086a2010-02-23 22:00:30 +00001668 // gcc rejects
1669 // class c {
1670 // static int a __attribute__((weakref ("v2")));
1671 // static int b() __attribute__((weakref ("f3")));
1672 // };
1673 // and ignores the attributes of
1674 // void f(void) {
1675 // static int a __attribute__((weakref ("v2")));
1676 // }
1677 // we reject them
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001678 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
Sebastian Redl50c68252010-08-31 00:36:30 +00001679 if (!Ctx->isFileContext()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00001680 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1681 << nd;
Sebastian Redl50c68252010-08-31 00:36:30 +00001682 return;
Rafael Espindolac18086a2010-02-23 22:00:30 +00001683 }
1684
1685 // The GCC manual says
1686 //
1687 // At present, a declaration to which `weakref' is attached can only
1688 // be `static'.
1689 //
1690 // It also says
1691 //
1692 // Without a TARGET,
1693 // given as an argument to `weakref' or to `alias', `weakref' is
1694 // equivalent to `weak'.
1695 //
1696 // gcc 4.4.1 will accept
1697 // int a7 __attribute__((weakref));
1698 // as
1699 // int a7 __attribute__((weak));
1700 // This looks like a bug in gcc. We reject that for now. We should revisit
1701 // it if this behaviour is actually used.
1702
Rafael Espindolac18086a2010-02-23 22:00:30 +00001703 // GCC rejects
1704 // static ((alias ("y"), weakref)).
1705 // Should we? How to check that weakref is before or after alias?
1706
Aaron Ballmanfebff0c2013-09-09 23:40:31 +00001707 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1708 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1709 // StringRef parameter it was given anyway.
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001710 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001711 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Rafael Espindolac18086a2010-02-23 22:00:30 +00001712 // GCC will accept anything as the argument of weakref. Should we
1713 // check for an existing decl?
Aaron Ballman3b1dde62013-09-13 19:35:18 +00001714 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1715 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001716
Michael Han99315932013-01-24 16:46:58 +00001717 D->addAttr(::new (S.Context)
1718 WeakRefAttr(Attr.getRange(), S.Context,
1719 Attr.getAttributeSpellingListIndex()));
Rafael Espindolac18086a2010-02-23 22:00:30 +00001720}
1721
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001722static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1723 StringRef Str;
1724 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1725 return;
1726
1727 // Aliases should be on declarations, not definitions.
1728 const auto *FD = cast<FunctionDecl>(D);
1729 if (FD->isThisDeclarationADefinition()) {
1730 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1731 return;
1732 }
1733 // FIXME: it should be handled as a target specific attribute.
1734 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1735 llvm::Triple::ELF) {
1736 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1737 return;
1738 }
1739
1740 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1741 Attr.getAttributeSpellingListIndex()));
1742}
1743
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001744static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1745 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00001746 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001747 return;
1748
Douglas Gregore8bbc122011-09-02 00:18:52 +00001749 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001750 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1751 return;
1752 }
Justin Lebara8f0254b2016-01-23 21:28:10 +00001753 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1754 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1755 }
Rafael Espindola0017c5f2010-12-07 15:23:23 +00001756
David Majnemer2dc81462015-01-19 09:00:28 +00001757 // Aliases should be on declarations, not definitions.
1758 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1759 if (FD->isThisDeclarationADefinition()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001760 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001761 return;
1762 }
1763 } else {
1764 const auto *VD = cast<VarDecl>(D);
1765 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001766 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
David Majnemer2dc81462015-01-19 09:00:28 +00001767 return;
1768 }
1769 }
1770
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001771 // FIXME: check if target symbol exists in current file
Mike Stumpd3bb5572009-07-24 19:02:52 +00001772
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001773 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00001774 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001775}
1776
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001777static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001778 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001779 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001780
Michael Han99315932013-01-24 16:46:58 +00001781 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1782 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001783}
1784
1785static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001786 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001787 return;
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001788
Michael Han99315932013-01-24 16:46:58 +00001789 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1790 Attr.getAttributeSpellingListIndex()));
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001791}
1792
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001793static void handleTLSModelAttr(Sema &S, Decl *D,
1794 const AttributeList &Attr) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001795 StringRef Model;
1796 SourceLocation LiteralLoc;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001797 // Check that it is a string.
Tim Northover6a6b63b2013-10-01 14:34:18 +00001798 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001799 return;
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001800
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001801 // Check that the value.
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001802 if (Model != "global-dynamic" && Model != "local-dynamic"
1803 && Model != "initial-exec" && Model != "local-exec") {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00001804 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001805 return;
1806 }
1807
Michael Han99315932013-01-24 16:46:58 +00001808 D->addAttr(::new (S.Context)
1809 TLSModelAttr(Attr.getRange(), S.Context, Model,
1810 Attr.getAttributeSpellingListIndex()));
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001811}
1812
David Majnemer631a90b2015-02-04 07:23:21 +00001813static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1814 QualType ResultType = getFunctionOrMethodResultType(D);
1815 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1816 D->addAttr(::new (S.Context) RestrictAttr(
1817 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1818 return;
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001819 }
1820
David Majnemer631a90b2015-02-04 07:23:21 +00001821 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1822 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
Ryan Flynn1f1fdc02009-08-09 20:07:29 +00001823}
1824
Chandler Carruthedc2c642011-07-02 00:01:44 +00001825static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001826 if (S.LangOpts.CPlusPlus) {
Aaron Ballman3db89662013-11-24 21:48:06 +00001827 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001828 << Attr.getName() << AttributeLangSupport::Cpp;
Eli Friedman6fc7ad12013-06-20 22:55:04 +00001829 return;
1830 }
1831
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001832 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1833 Attr.getAttributeSpellingListIndex()))
1834 D->addAttr(CA);
Eric Christopher8a2ee392010-12-02 02:45:55 +00001835}
1836
Charles Davis0e379112016-08-08 21:19:08 +00001837static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1838 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1839 Attr.getName()))
1840 return;
1841
1842 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1843 Attr.getAttributeSpellingListIndex()));
1844}
1845
Chandler Carruthedc2c642011-07-02 00:01:44 +00001846static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001847 if (hasDeclarator(D)) return;
John McCall3882ace2011-01-05 12:14:39 +00001848
1849 if (S.CheckNoReturnAttr(attr)) return;
1850
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001851 if (!isa<ObjCMethodDecl>(D)) {
John McCall3882ace2011-01-05 12:14:39 +00001852 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001853 << attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00001854 return;
1855 }
1856
Michael Han99315932013-01-24 16:46:58 +00001857 D->addAttr(::new (S.Context)
1858 NoReturnAttr(attr.getRange(), S.Context,
1859 attr.getAttributeSpellingListIndex()));
John McCall3882ace2011-01-05 12:14:39 +00001860}
1861
1862bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00001863 if (!checkAttributeNumArgs(*this, attr, 0)) {
John McCall3882ace2011-01-05 12:14:39 +00001864 attr.setInvalid();
1865 return true;
1866 }
1867
1868 return false;
Ted Kremenek40f4ee72009-04-10 00:01:14 +00001869}
1870
Chandler Carruthedc2c642011-07-02 00:01:44 +00001871static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1872 const AttributeList &Attr) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00001873
1874 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1875 // because 'analyzer_noreturn' does not impact the type.
David Majnemer06864812015-04-07 06:01:53 +00001876 if (!isFunctionOrMethodOrBlock(D)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001877 ValueDecl *VD = dyn_cast<ValueDecl>(D);
Craig Topperc3ec1492014-05-26 06:22:03 +00001878 if (!VD || (!VD->getType()->isBlockPointerType() &&
1879 !VD->getType()->isFunctionPointerType())) {
Ted Kremenek5295ce82010-08-19 00:51:58 +00001880 S.Diag(Attr.getLoc(),
Richard Smith89645bc2013-01-02 12:01:23 +00001881 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
Craig Topper8f7f3ea2015-11-17 05:40:05 +00001882 : diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001883 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Ted Kremenek5295ce82010-08-19 00:51:58 +00001884 return;
1885 }
1886 }
1887
Michael Han99315932013-01-24 16:46:58 +00001888 D->addAttr(::new (S.Context)
1889 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1890 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00001891}
1892
John Thompsoncdb847ba2010-08-09 21:53:52 +00001893// PS3 PPU-specific.
Chandler Carruthedc2c642011-07-02 00:01:44 +00001894static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John Thompsoncdb847ba2010-08-09 21:53:52 +00001895/*
1896 Returning a Vector Class in Registers
1897
Eric Christopherbc638a82010-12-01 22:13:54 +00001898 According to the PPU ABI specifications, a class with a single member of
1899 vector type is returned in memory when used as the return value of a function.
1900 This results in inefficient code when implementing vector classes. To return
1901 the value in a single vector register, add the vecreturn attribute to the
1902 class definition. This attribute is also applicable to struct types.
John Thompsoncdb847ba2010-08-09 21:53:52 +00001903
1904 Example:
1905
1906 struct Vector
1907 {
1908 __vector float xyzw;
1909 } __attribute__((vecreturn));
1910
1911 Vector Add(Vector lhs, Vector rhs)
1912 {
1913 Vector result;
1914 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1915 return result; // This will be returned in a register
1916 }
1917*/
Aaron Ballman3e424b52013-12-26 18:30:57 +00001918 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1919 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
John Thompsoncdb847ba2010-08-09 21:53:52 +00001920 return;
1921 }
1922
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001923 RecordDecl *record = cast<RecordDecl>(D);
John Thompson9a587aaa2010-09-18 01:12:07 +00001924 int count = 0;
1925
1926 if (!isa<CXXRecordDecl>(record)) {
1927 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1928 return;
1929 }
1930
1931 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1932 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1933 return;
1934 }
1935
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001936 for (const auto *I : record->fields()) {
1937 if ((count == 1) || !I->getType()->isVectorType()) {
John Thompson9a587aaa2010-09-18 01:12:07 +00001938 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1939 return;
1940 }
1941 count++;
1942 }
1943
Michael Han99315932013-01-24 16:46:58 +00001944 D->addAttr(::new (S.Context)
1945 VecReturnAttr(Attr.getRange(), S.Context,
1946 Attr.getAttributeSpellingListIndex()));
John Thompsoncdb847ba2010-08-09 21:53:52 +00001947}
1948
Richard Smithe233fbf2013-01-28 22:42:45 +00001949static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1950 const AttributeList &Attr) {
1951 if (isa<ParmVarDecl>(D)) {
1952 // [[carries_dependency]] can only be applied to a parameter if it is a
1953 // parameter of a function declaration or lambda.
1954 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1955 S.Diag(Attr.getLoc(),
1956 diag::err_carries_dependency_param_not_function_decl);
1957 return;
1958 }
Alexis Hunt96d5c762009-11-21 08:43:09 +00001959 }
Richard Smithe233fbf2013-01-28 22:42:45 +00001960
1961 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1962 Attr.getRange(), S.Context,
1963 Attr.getAttributeSpellingListIndex()));
Alexis Hunt96d5c762009-11-21 08:43:09 +00001964}
1965
Akira Hatanakac8667622015-11-06 23:56:15 +00001966static void handleNotTailCalledAttr(Sema &S, Decl *D,
1967 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001968 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
1969 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00001970 return;
1971
1972 D->addAttr(::new (S.Context) NotTailCalledAttr(
1973 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1974}
1975
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00001976static void handleDisableTailCallsAttr(Sema &S, Decl *D,
1977 const AttributeList &Attr) {
1978 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
1979 Attr.getName()))
1980 return;
1981
1982 D->addAttr(::new (S.Context) DisableTailCallsAttr(
1983 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1984}
1985
Chandler Carruthedc2c642011-07-02 00:01:44 +00001986static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001987 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola87198cd2013-08-16 23:18:50 +00001988 if (VD->hasLocalStorage()) {
Aaron Ballman88fe3222013-12-26 17:30:44 +00001989 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001990 return;
1991 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00001992 } else if (!isFunctionOrMethod(D)) {
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001993 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00001994 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbarfee07a02009-02-13 19:23:53 +00001995 return;
1996 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00001997
Michael Han99315932013-01-24 16:46:58 +00001998 D->addAttr(::new (S.Context)
1999 UsedAttr(Attr.getRange(), S.Context,
2000 Attr.getAttributeSpellingListIndex()));
Daniel Dunbarfee07a02009-02-13 19:23:53 +00002001}
2002
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00002003static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2004 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2005
2006 if (IsCXX1zAttr && isa<VarDecl>(D)) {
2007 // The C++1z spelling of this attribute cannot be applied to a static data
2008 // member per [dcl.attr.unused]p2.
2009 if (cast<VarDecl>(D)->isStaticDataMember()) {
2010 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2011 << Attr.getName() << ExpectedForMaybeUnused;
2012 return;
2013 }
2014 }
2015
2016 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2017 // about using it as an extension.
2018 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
2019 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2020
2021 D->addAttr(::new (S.Context) UnusedAttr(
2022 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2023}
2024
Chandler Carruthedc2c642011-07-02 00:01:44 +00002025static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002026 uint32_t priority = ConstructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002027 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002028 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2029 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002030
Michael Han99315932013-01-24 16:46:58 +00002031 D->addAttr(::new (S.Context)
2032 ConstructorAttr(Attr.getRange(), S.Context, priority,
2033 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002034}
2035
Chandler Carruthedc2c642011-07-02 00:01:44 +00002036static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmanf28e4992014-01-20 15:22:57 +00002037 uint32_t priority = DestructorAttr::DefaultPriority;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002038 if (Attr.getNumArgs() &&
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002039 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2040 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002041
Michael Han99315932013-01-24 16:46:58 +00002042 D->addAttr(::new (S.Context)
2043 DestructorAttr(Attr.getRange(), S.Context, priority,
2044 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar032db472008-07-31 22:40:48 +00002045}
2046
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002047template <typename AttrTy>
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00002048static void handleAttrWithMessage(Sema &S, Decl *D,
2049 const AttributeList &Attr) {
Benjamin Kramerf435ab42012-05-16 12:19:08 +00002050 // Handle the case where the attribute has a text message.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002051 StringRef Str;
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00002052 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002053 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002054
Michael Han99315932013-01-24 16:46:58 +00002055 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2056 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian1470e932008-12-17 01:07:27 +00002057}
2058
Ted Kremenek438f8db2014-02-22 01:06:05 +00002059static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
Ted Kremenek28eace62013-11-23 01:01:34 +00002060 const AttributeList &Attr) {
Ted Kremenek438f8db2014-02-22 01:06:05 +00002061 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
Ted Kremenek27cfe102014-02-21 22:49:04 +00002062 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2063 << Attr.getName() << Attr.getRange();
2064 return;
2065 }
2066
Ted Kremenek28eace62013-11-23 01:01:34 +00002067 D->addAttr(::new (S.Context)
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00002068 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2069 Attr.getAttributeSpellingListIndex()));
Ted Kremenek28eace62013-11-23 01:01:34 +00002070}
2071
Jordy Rose740b0c22012-05-08 03:27:22 +00002072static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2073 IdentifierInfo *Platform,
2074 VersionTuple Introduced,
2075 VersionTuple Deprecated,
2076 VersionTuple Obsoleted) {
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002077 StringRef PlatformName
2078 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2079 if (PlatformName.empty())
2080 PlatformName = Platform->getName();
2081
2082 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2083 // of these steps are needed).
2084 if (!Introduced.empty() && !Deprecated.empty() &&
2085 !(Introduced <= Deprecated)) {
2086 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2087 << 1 << PlatformName << Deprecated.getAsString()
2088 << 0 << Introduced.getAsString();
2089 return true;
2090 }
2091
2092 if (!Introduced.empty() && !Obsoleted.empty() &&
2093 !(Introduced <= Obsoleted)) {
2094 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2095 << 2 << PlatformName << Obsoleted.getAsString()
2096 << 0 << Introduced.getAsString();
2097 return true;
2098 }
2099
2100 if (!Deprecated.empty() && !Obsoleted.empty() &&
2101 !(Deprecated <= Obsoleted)) {
2102 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2103 << 2 << PlatformName << Obsoleted.getAsString()
2104 << 1 << Deprecated.getAsString();
2105 return true;
2106 }
2107
2108 return false;
2109}
2110
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002111/// \brief Check whether the two versions match.
2112///
2113/// If either version tuple is empty, then they are assumed to match. If
2114/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2115static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2116 bool BeforeIsOkay) {
2117 if (X.empty() || Y.empty())
2118 return true;
2119
2120 if (X == Y)
2121 return true;
2122
2123 if (BeforeIsOkay && X < Y)
2124 return true;
2125
2126 return false;
2127}
2128
Rafael Espindolaa3aea432013-01-08 22:04:34 +00002129AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002130 IdentifierInfo *Platform,
Manman Ren719a8642016-05-06 21:04:01 +00002131 bool Implicit,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002132 VersionTuple Introduced,
2133 VersionTuple Deprecated,
2134 VersionTuple Obsoleted,
2135 bool IsUnavailable,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002136 StringRef Message,
Manman Rend8039df2016-02-22 04:47:24 +00002137 bool IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002138 StringRef Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002139 AvailabilityMergeKind AMK,
Michael Han99315932013-01-24 16:46:58 +00002140 unsigned AttrSpellingListIndex) {
Rafael Espindolac67f2232012-05-10 02:50:16 +00002141 VersionTuple MergedIntroduced = Introduced;
2142 VersionTuple MergedDeprecated = Deprecated;
2143 VersionTuple MergedObsoleted = Obsoleted;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002144 bool FoundAny = false;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002145 bool OverrideOrImpl = false;
2146 switch (AMK) {
2147 case AMK_None:
2148 case AMK_Redeclaration:
2149 OverrideOrImpl = false;
2150 break;
2151
2152 case AMK_Override:
2153 case AMK_ProtocolImplementation:
2154 OverrideOrImpl = true;
2155 break;
2156 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002157
Rafael Espindolac67f2232012-05-10 02:50:16 +00002158 if (D->hasAttrs()) {
2159 AttrVec &Attrs = D->getAttrs();
2160 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2161 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2162 if (!OldAA) {
2163 ++i;
2164 continue;
2165 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002166
Rafael Espindolac67f2232012-05-10 02:50:16 +00002167 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2168 if (OldPlatform != Platform) {
2169 ++i;
2170 continue;
2171 }
2172
Tim Northover7a73cc72015-10-30 16:30:49 +00002173 // If there is an existing availability attribute for this platform that
2174 // is explicit and the new one is implicit use the explicit one and
2175 // discard the new implicit attribute.
Manman Ren719a8642016-05-06 21:04:01 +00002176 if (!OldAA->isImplicit() && Implicit) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002177 return nullptr;
2178 }
2179
2180 // If there is an existing attribute for this platform that is implicit
2181 // and the new attribute is explicit then erase the old one and
2182 // continue processing the attributes.
Manman Ren719a8642016-05-06 21:04:01 +00002183 if (!Implicit && OldAA->isImplicit()) {
Tim Northover7a73cc72015-10-30 16:30:49 +00002184 Attrs.erase(Attrs.begin() + i);
2185 --e;
2186 continue;
2187 }
2188
Rafael Espindolac67f2232012-05-10 02:50:16 +00002189 FoundAny = true;
2190 VersionTuple OldIntroduced = OldAA->getIntroduced();
2191 VersionTuple OldDeprecated = OldAA->getDeprecated();
2192 VersionTuple OldObsoleted = OldAA->getObsoleted();
2193 bool OldIsUnavailable = OldAA->getUnavailable();
Rafael Espindolac67f2232012-05-10 02:50:16 +00002194
Douglas Gregord2a713e2015-09-30 21:27:42 +00002195 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2196 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2197 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002198 !(OldIsUnavailable == IsUnavailable ||
Douglas Gregord2a713e2015-09-30 21:27:42 +00002199 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2200 if (OverrideOrImpl) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002201 int Which = -1;
2202 VersionTuple FirstVersion;
2203 VersionTuple SecondVersion;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002204 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002205 Which = 0;
2206 FirstVersion = OldIntroduced;
2207 SecondVersion = Introduced;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002208 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002209 Which = 1;
2210 FirstVersion = Deprecated;
2211 SecondVersion = OldDeprecated;
Douglas Gregord2a713e2015-09-30 21:27:42 +00002212 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002213 Which = 2;
2214 FirstVersion = Obsoleted;
2215 SecondVersion = OldObsoleted;
2216 }
2217
2218 if (Which == -1) {
2219 Diag(OldAA->getLocation(),
2220 diag::warn_mismatched_availability_override_unavail)
Douglas Gregord2a713e2015-09-30 21:27:42 +00002221 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2222 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002223 } else {
2224 Diag(OldAA->getLocation(),
2225 diag::warn_mismatched_availability_override)
2226 << Which
2227 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
Douglas Gregord2a713e2015-09-30 21:27:42 +00002228 << FirstVersion.getAsString() << SecondVersion.getAsString()
2229 << (AMK == AMK_Override);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002230 }
Douglas Gregord2a713e2015-09-30 21:27:42 +00002231 if (AMK == AMK_Override)
2232 Diag(Range.getBegin(), diag::note_overridden_method);
2233 else
2234 Diag(Range.getBegin(), diag::note_protocol_method);
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002235 } else {
2236 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2237 Diag(Range.getBegin(), diag::note_previous_attribute);
2238 }
2239
Rafael Espindolac67f2232012-05-10 02:50:16 +00002240 Attrs.erase(Attrs.begin() + i);
2241 --e;
2242 continue;
2243 }
2244
2245 VersionTuple MergedIntroduced2 = MergedIntroduced;
2246 VersionTuple MergedDeprecated2 = MergedDeprecated;
2247 VersionTuple MergedObsoleted2 = MergedObsoleted;
2248
2249 if (MergedIntroduced2.empty())
2250 MergedIntroduced2 = OldIntroduced;
2251 if (MergedDeprecated2.empty())
2252 MergedDeprecated2 = OldDeprecated;
2253 if (MergedObsoleted2.empty())
2254 MergedObsoleted2 = OldObsoleted;
2255
2256 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2257 MergedIntroduced2, MergedDeprecated2,
2258 MergedObsoleted2)) {
2259 Attrs.erase(Attrs.begin() + i);
2260 --e;
2261 continue;
2262 }
2263
2264 MergedIntroduced = MergedIntroduced2;
2265 MergedDeprecated = MergedDeprecated2;
2266 MergedObsoleted = MergedObsoleted2;
2267 ++i;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002268 }
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002269 }
2270
2271 if (FoundAny &&
2272 MergedIntroduced == Introduced &&
2273 MergedDeprecated == Deprecated &&
2274 MergedObsoleted == Obsoleted)
Craig Topperc3ec1492014-05-26 06:22:03 +00002275 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002276
Douglas Gregord2a713e2015-09-30 21:27:42 +00002277 // Only create a new attribute if !OverrideOrImpl, but we want to do
Ted Kremenekb5445722013-04-06 00:34:27 +00002278 // the checking.
Rafael Espindolac67f2232012-05-10 02:50:16 +00002279 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
Ted Kremenekb5445722013-04-06 00:34:27 +00002280 MergedDeprecated, MergedObsoleted) &&
Douglas Gregord2a713e2015-09-30 21:27:42 +00002281 !OverrideOrImpl) {
Manman Ren719a8642016-05-06 21:04:01 +00002282 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002283 Introduced, Deprecated,
Michael Han99315932013-01-24 16:46:58 +00002284 Obsoleted, IsUnavailable, Message,
Manman Ren75bc6762016-03-21 17:30:55 +00002285 IsStrict, Replacement,
2286 AttrSpellingListIndex);
Manman Ren719a8642016-05-06 21:04:01 +00002287 Avail->setImplicit(Implicit);
2288 return Avail;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002289 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002290 return nullptr;
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002291}
2292
Chandler Carruthedc2c642011-07-02 00:01:44 +00002293static void handleAvailabilityAttr(Sema &S, Decl *D,
2294 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002295 if (!checkAttributeNumArgs(S, Attr, 1))
2296 return;
2297 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
Michael Han99315932013-01-24 16:46:58 +00002298 unsigned Index = Attr.getAttributeSpellingListIndex();
2299
Aaron Ballman00e99962013-08-31 01:11:41 +00002300 IdentifierInfo *II = Platform->Ident;
2301 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2302 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2303 << Platform->Ident;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002304
Rafael Espindolac231fab2013-01-08 21:30:32 +00002305 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2306 if (!ND) {
2307 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2308 return;
2309 }
2310
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002311 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2312 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2313 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
Douglas Gregor7ab142b2011-03-26 03:35:55 +00002314 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
Manman Rend8039df2016-02-22 04:47:24 +00002315 bool IsStrict = Attr.getStrictLoc().isValid();
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002316 StringRef Str;
Benjamin Kramera9dfa922013-09-13 17:31:48 +00002317 if (const StringLiteral *SE =
2318 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
Fariborz Jahanian88d510d2011-12-10 00:28:41 +00002319 Str = SE->getString();
Manman Ren75bc6762016-03-21 17:30:55 +00002320 StringRef Replacement;
2321 if (const StringLiteral *SE =
2322 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2323 Replacement = SE->getString();
Rafael Espindola2d243bf2012-05-06 19:56:25 +00002324
Aaron Ballman00e99962013-08-31 01:11:41 +00002325 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
Manman Ren719a8642016-05-06 21:04:01 +00002326 false/*Implicit*/,
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002327 Introduced.Version,
2328 Deprecated.Version,
2329 Obsoleted.Version,
Douglas Gregor66a8ca02013-01-15 22:43:08 +00002330 IsUnavailable, Str,
Manman Ren75bc6762016-03-21 17:30:55 +00002331 IsStrict, Replacement,
Douglas Gregord2a713e2015-09-30 21:27:42 +00002332 Sema::AMK_None,
Michael Han99315932013-01-24 16:46:58 +00002333 Index);
Rafael Espindola19de5612013-01-12 06:42:30 +00002334 if (NewAttr)
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002335 D->addAttr(NewAttr);
Tim Northover7a73cc72015-10-30 16:30:49 +00002336
2337 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2338 // matches before the start of the watchOS platform.
2339 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2340 IdentifierInfo *NewII = nullptr;
2341 if (II->getName() == "ios")
2342 NewII = &S.Context.Idents.get("watchos");
2343 else if (II->getName() == "ios_app_extension")
2344 NewII = &S.Context.Idents.get("watchos_app_extension");
2345
2346 if (NewII) {
2347 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2348 if (Version.empty())
2349 return Version;
2350 auto Major = Version.getMajor();
2351 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2352 if (NewMajor >= 2) {
2353 if (Version.getMinor().hasValue()) {
2354 if (Version.getSubminor().hasValue())
2355 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2356 Version.getSubminor().getValue());
2357 else
2358 return VersionTuple(NewMajor, Version.getMinor().getValue());
2359 }
2360 }
2361
2362 return VersionTuple(2, 0);
2363 };
2364
2365 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2366 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2367 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2368
2369 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002370 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002371 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002372 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002373 NewIntroduced,
2374 NewDeprecated,
2375 NewObsoleted,
2376 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002377 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002378 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002379 Sema::AMK_None,
2380 Index);
2381 if (NewAttr)
2382 D->addAttr(NewAttr);
2383 }
2384 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2385 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2386 // matches before the start of the tvOS platform.
2387 IdentifierInfo *NewII = nullptr;
2388 if (II->getName() == "ios")
2389 NewII = &S.Context.Idents.get("tvos");
2390 else if (II->getName() == "ios_app_extension")
2391 NewII = &S.Context.Idents.get("tvos_app_extension");
2392
2393 if (NewII) {
2394 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
Manman Ren719a8642016-05-06 21:04:01 +00002395 Attr.getRange(),
Tim Northover7a73cc72015-10-30 16:30:49 +00002396 NewII,
Manman Ren719a8642016-05-06 21:04:01 +00002397 true/*Implicit*/,
Tim Northover7a73cc72015-10-30 16:30:49 +00002398 Introduced.Version,
2399 Deprecated.Version,
2400 Obsoleted.Version,
2401 IsUnavailable, Str,
Manman Rend8039df2016-02-22 04:47:24 +00002402 IsStrict,
Manman Ren75bc6762016-03-21 17:30:55 +00002403 Replacement,
Tim Northover7a73cc72015-10-30 16:30:49 +00002404 Sema::AMK_None,
2405 Index);
2406 if (NewAttr)
2407 D->addAttr(NewAttr);
2408 }
2409 }
Rafael Espindolac67f2232012-05-10 02:50:16 +00002410}
2411
Alex Lorenzd5d27e12017-03-01 18:06:25 +00002412static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2413 const AttributeList &Attr) {
2414 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2415 return;
2416 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2417 "Invalid number of arguments in an external_source_symbol attribute");
2418
2419 if (!isa<NamedDecl>(D)) {
2420 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2421 << Attr.getName() << ExpectedNamedDecl;
2422 return;
2423 }
2424
2425 StringRef Language;
2426 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2427 Language = SE->getString();
2428 StringRef DefinedIn;
2429 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2430 DefinedIn = SE->getString();
2431 bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2432
2433 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2434 Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2435 Attr.getAttributeSpellingListIndex()));
2436}
2437
John McCalld041a9b2013-02-20 01:54:26 +00002438template <class T>
2439static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2440 typename T::VisibilityType value,
2441 unsigned attrSpellingListIndex) {
2442 T *existingAttr = D->getAttr<T>();
2443 if (existingAttr) {
2444 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2445 if (existingValue == value)
Craig Topperc3ec1492014-05-26 06:22:03 +00002446 return nullptr;
John McCalld041a9b2013-02-20 01:54:26 +00002447 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2448 S.Diag(range.getBegin(), diag::note_previous_attribute);
2449 D->dropAttr<T>();
2450 }
2451 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2452}
2453
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002454VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002455 VisibilityAttr::VisibilityType Vis,
2456 unsigned AttrSpellingListIndex) {
John McCalld041a9b2013-02-20 01:54:26 +00002457 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2458 AttrSpellingListIndex);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002459}
2460
John McCalld041a9b2013-02-20 01:54:26 +00002461TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2462 TypeVisibilityAttr::VisibilityType Vis,
2463 unsigned AttrSpellingListIndex) {
2464 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2465 AttrSpellingListIndex);
2466}
2467
2468static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2469 bool isTypeVisibility) {
2470 // Visibility attributes don't mean anything on a typedef.
2471 if (isa<TypedefNameDecl>(D)) {
2472 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2473 << Attr.getName();
2474 return;
2475 }
2476
2477 // 'type_visibility' can only go on a type or namespace.
2478 if (isTypeVisibility &&
2479 !(isa<TagDecl>(D) ||
2480 isa<ObjCInterfaceDecl>(D) ||
2481 isa<NamespaceDecl>(D))) {
2482 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2483 << Attr.getName() << ExpectedTypeOrNamespace;
2484 return;
2485 }
2486
Benjamin Kramer70370212013-09-09 15:08:57 +00002487 // Check that the argument is a string literal.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002488 StringRef TypeStr;
2489 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002490 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002491 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002492
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002493 VisibilityAttr::VisibilityType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002494 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002495 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
Aaron Ballman682ee422013-09-11 19:47:58 +00002496 << Attr.getName() << TypeStr;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002497 return;
2498 }
Aaron Ballman682ee422013-09-11 19:47:58 +00002499
2500 // Complain about attempts to use protected visibility on targets
2501 // (like Darwin) that don't support it.
2502 if (type == VisibilityAttr::Protected &&
2503 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2504 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2505 type = VisibilityAttr::Default;
2506 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002507
Michael Han99315932013-01-24 16:46:58 +00002508 unsigned Index = Attr.getAttributeSpellingListIndex();
John McCalld041a9b2013-02-20 01:54:26 +00002509 clang::Attr *newAttr;
2510 if (isTypeVisibility) {
2511 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2512 (TypeVisibilityAttr::VisibilityType) type,
2513 Index);
2514 } else {
2515 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2516 }
2517 if (newAttr)
2518 D->addAttr(newAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00002519}
2520
Chandler Carruthedc2c642011-07-02 00:01:44 +00002521static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2522 const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002523 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
Aaron Ballman00e99962013-08-31 01:11:41 +00002524 if (!Attr.isArgIdent(0)) {
2525 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2526 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
John McCall86bc21f2011-03-02 11:33:24 +00002527 return;
2528 }
Aaron Ballman00e99962013-08-31 01:11:41 +00002529
Aaron Ballman682ee422013-09-11 19:47:58 +00002530 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2531 ObjCMethodFamilyAttr::FamilyKind F;
2532 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2533 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2534 << IL->Ident;
John McCall86bc21f2011-03-02 11:33:24 +00002535 return;
2536 }
2537
Alp Toker314cc812014-01-25 16:55:45 +00002538 if (F == ObjCMethodFamilyAttr::OMF_init &&
2539 !method->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002540 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
Alp Toker314cc812014-01-25 16:55:45 +00002541 << method->getReturnType();
John McCall31168b02011-06-15 23:02:42 +00002542 // Ignore the attribute.
2543 return;
2544 }
2545
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00002546 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
Aaron Ballman36a53502014-01-16 13:03:14 +00002547 S.Context, F,
2548 Attr.getAttributeSpellingListIndex()));
John McCall86bc21f2011-03-02 11:33:24 +00002549}
2550
Chandler Carruthedc2c642011-07-02 00:01:44 +00002551static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
Richard Smithdda56e42011-04-15 14:24:37 +00002552 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002553 QualType T = TD->getUnderlyingType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002554 if (!T->isCARCBridgableType()) {
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002555 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2556 return;
2557 }
2558 }
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002559 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2560 QualType T = PD->getType();
Ted Kremenek7712eef2012-08-29 22:54:47 +00002561 if (!T->isCARCBridgableType()) {
Fariborz Jahanianbebd0ba2012-05-31 23:18:32 +00002562 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2563 return;
2564 }
2565 }
2566 else {
Ted Kremenek05e916b2012-03-01 01:40:32 +00002567 // It is okay to include this attribute on properties, e.g.:
2568 //
2569 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2570 //
2571 // In this case it follows tradition and suppresses an error in the above
2572 // case.
Fariborz Jahaniana45495a2011-11-29 01:48:40 +00002573 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
Ted Kremenek05e916b2012-03-01 01:40:32 +00002574 }
Michael Han99315932013-01-24 16:46:58 +00002575 D->addAttr(::new (S.Context)
2576 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2577 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian255c0952009-01-13 23:34:40 +00002578}
2579
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00002580static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2581 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2582 QualType T = TD->getUnderlyingType();
2583 if (!T->isObjCObjectPointerType()) {
2584 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2585 return;
2586 }
2587 } else {
2588 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2589 return;
2590 }
2591 D->addAttr(::new (S.Context)
2592 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2593 Attr.getAttributeSpellingListIndex()));
2594}
2595
Chandler Carruthedc2c642011-07-02 00:01:44 +00002596static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002597 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002598 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00002599 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Steve Naroff3405a732008-09-18 16:44:58 +00002600 return;
2601 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002602
Aaron Ballman00e99962013-08-31 01:11:41 +00002603 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002604 BlocksAttr::BlockType type;
Aaron Ballman682ee422013-09-11 19:47:58 +00002605 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2606 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2607 << Attr.getName() << II;
Steve Naroff3405a732008-09-18 16:44:58 +00002608 return;
2609 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002610
Michael Han99315932013-01-24 16:46:58 +00002611 D->addAttr(::new (S.Context)
2612 BlocksAttr(Attr.getRange(), S.Context, type,
2613 Attr.getAttributeSpellingListIndex()));
Steve Naroff3405a732008-09-18 16:44:58 +00002614}
2615
Chandler Carruthedc2c642011-07-02 00:01:44 +00002616static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman18a78382013-11-21 00:28:23 +00002617 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
Anders Carlssonc181b012008-10-05 18:05:59 +00002618 if (Attr.getNumArgs() > 0) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002619 Expr *E = Attr.getArgAsExpr(0);
Anders Carlssonc181b012008-10-05 18:05:59 +00002620 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002621 if (E->isTypeDependent() || E->isValueDependent() ||
2622 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002623 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002624 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002625 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002626 return;
2627 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002628
John McCallb46f2872011-09-09 07:56:05 +00002629 if (Idx.isSigned() && Idx.isNegative()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002630 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2631 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002632 return;
2633 }
John McCallb46f2872011-09-09 07:56:05 +00002634
2635 sentinel = Idx.getZExtValue();
Anders Carlssonc181b012008-10-05 18:05:59 +00002636 }
2637
Aaron Ballman18a78382013-11-21 00:28:23 +00002638 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
Anders Carlssonc181b012008-10-05 18:05:59 +00002639 if (Attr.getNumArgs() > 1) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002640 Expr *E = Attr.getArgAsExpr(1);
Anders Carlssonc181b012008-10-05 18:05:59 +00002641 llvm::APSInt Idx(32);
Douglas Gregorbdb604a2010-05-18 23:01:22 +00002642 if (E->isTypeDependent() || E->isValueDependent() ||
2643 !E->isIntegerConstantExpr(Idx, S.Context)) {
Aaron Ballman29982272013-07-23 14:03:57 +00002644 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00002645 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
Aaron Ballman29982272013-07-23 14:03:57 +00002646 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002647 return;
2648 }
2649 nullPos = Idx.getZExtValue();
Mike Stumpd3bb5572009-07-24 19:02:52 +00002650
John McCallb46f2872011-09-09 07:56:05 +00002651 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002652 // FIXME: This error message could be improved, it would be nice
2653 // to say what the bounds actually are.
Chris Lattner3b054132008-11-19 05:08:23 +00002654 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2655 << E->getSourceRange();
Anders Carlssonc181b012008-10-05 18:05:59 +00002656 return;
2657 }
2658 }
2659
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002660 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +00002661 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
Chris Lattner9363e312009-03-17 23:03:47 +00002662 if (isa<FunctionNoProtoType>(FT)) {
2663 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2664 return;
2665 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002666
Chris Lattner9363e312009-03-17 23:03:47 +00002667 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002668 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002669 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002670 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002671 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Anders Carlssonc181b012008-10-05 18:05:59 +00002672 if (!MD->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002673 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
Anders Carlssonc181b012008-10-05 18:05:59 +00002674 return;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002675 }
Eli Friedman5c5e3b72012-01-06 01:23:10 +00002676 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2677 if (!BD->isVariadic()) {
2678 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2679 return;
2680 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002681 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002682 QualType Ty = V->getType();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002683 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Aaron Ballman12b9f652014-01-16 13:55:42 +00002684 const FunctionType *FT = Ty->isFunctionPointerType()
2685 ? D->getFunctionType()
Eric Christopherbc638a82010-12-01 22:13:54 +00002686 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002687 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00002688 int m = Ty->isFunctionPointerType() ? 0 : 1;
2689 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002690 return;
2691 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002692 } else {
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002693 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002694 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00002695 return;
2696 }
Anders Carlssonc181b012008-10-05 18:05:59 +00002697 } else {
Chris Lattner3b054132008-11-19 05:08:23 +00002698 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002699 << Attr.getName() << ExpectedFunctionMethodOrBlock;
Anders Carlssonc181b012008-10-05 18:05:59 +00002700 return;
2701 }
Michael Han99315932013-01-24 16:46:58 +00002702 D->addAttr(::new (S.Context)
2703 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2704 Attr.getAttributeSpellingListIndex()));
Anders Carlssonc181b012008-10-05 18:05:59 +00002705}
2706
Chandler Carruthedc2c642011-07-02 00:01:44 +00002707static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
Alp Toker314cc812014-01-25 16:55:45 +00002708 if (D->getFunctionType() &&
2709 D->getFunctionType()->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002710 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2711 << Attr.getName() << 0;
Nuno Lopes56abcbd2009-12-22 23:59:52 +00002712 return;
2713 }
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002714 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00002715 if (MD->getReturnType()->isVoidType()) {
Fariborz Jahanian5cab26d2010-03-30 18:22:15 +00002716 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2717 << Attr.getName() << 1;
2718 return;
2719 }
2720
Aaron Ballmane7964782016-03-07 22:44:55 +00002721 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2722 // about using it as an extension.
2723 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2724 !Attr.getScopeName())
Richard Smith4f902c72016-03-08 00:32:55 +00002725 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
Aaron Ballmane7964782016-03-07 22:44:55 +00002726
Michael Han99315932013-01-24 16:46:58 +00002727 D->addAttr(::new (S.Context)
2728 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2729 Attr.getAttributeSpellingListIndex()));
Chris Lattner237f2752009-02-14 07:37:35 +00002730}
2731
Chandler Carruthedc2c642011-07-02 00:01:44 +00002732static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002733 // weak_import only applies to variable & function declarations.
2734 bool isDef = false;
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002735 if (!D->canBeWeakImported(isDef)) {
2736 if (isDef)
Reid Kleckner52d598e2013-05-20 21:53:29 +00002737 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2738 << "weak_import";
Douglas Gregord71149a2011-03-23 13:27:51 +00002739 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00002740 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
Fariborz Jahanian3249a1e2011-10-26 23:59:12 +00002741 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
Douglas Gregord71149a2011-03-23 13:27:51 +00002742 // Nothing to warn about here.
2743 } else
Fariborz Jahanianea70a172010-04-13 20:22:35 +00002744 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00002745 << Attr.getName() << ExpectedVariableOrFunction;
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002746
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002747 return;
2748 }
2749
Michael Han99315932013-01-24 16:46:58 +00002750 D->addAttr(::new (S.Context)
2751 WeakImportAttr(Attr.getRange(), S.Context,
2752 Attr.getAttributeSpellingListIndex()));
Daniel Dunbar5cb85eb2009-03-06 06:39:57 +00002753}
2754
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002755// Handles reqd_work_group_size and work_group_size_hint.
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002756template <typename WorkGroupAttr>
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002757static void handleWorkGroupSize(Sema &S, Decl *D,
Nick Lewyckyb9e4a3a2012-07-24 01:31:55 +00002758 const AttributeList &Attr) {
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00002759 uint32_t WGSize[3];
Joey Goulyb1d23a82014-05-19 14:41:38 +00002760 for (unsigned i = 0; i < 3; ++i) {
2761 const Expr *E = Attr.getArgAsExpr(i);
2762 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
Nate Begemanf2758702009-06-26 06:32:41 +00002763 return;
Joey Goulyb1d23a82014-05-19 14:41:38 +00002764 if (WGSize[i] == 0) {
2765 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2766 << Attr.getName() << E->getSourceRange();
2767 return;
2768 }
2769 }
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002770
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002771 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2772 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2773 Existing->getYDim() == WGSize[1] &&
2774 Existing->getZDim() == WGSize[2]))
2775 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00002776
Aaron Ballman1d0d2a42013-12-02 22:38:33 +00002777 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2778 WGSize[0], WGSize[1], WGSize[2],
Michael Han99315932013-01-24 16:46:58 +00002779 Attr.getAttributeSpellingListIndex()));
Nate Begemanf2758702009-06-26 06:32:41 +00002780}
2781
Joey Goulyaba589c2013-03-08 09:42:32 +00002782static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002783 if (!Attr.hasParsedType()) {
2784 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2785 << Attr.getName() << 1;
2786 return;
2787 }
2788
Craig Topperc3ec1492014-05-26 06:22:03 +00002789 TypeSourceInfo *ParmTSI = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00002790 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2791 assert(ParmTSI && "no type source info for attribute argument");
Joey Goulyaba589c2013-03-08 09:42:32 +00002792
2793 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2794 (ParmType->isBooleanType() ||
2795 !ParmType->isIntegralType(S.getASTContext()))) {
2796 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2797 << ParmType;
2798 return;
2799 }
2800
Aaron Ballmana9e05402013-12-02 22:16:55 +00002801 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
Richard Smithb87c4652013-10-31 21:23:20 +00002802 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
Joey Goulyaba589c2013-03-08 09:42:32 +00002803 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2804 return;
2805 }
2806 }
2807
2808 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
Aaron Ballman36a53502014-01-16 13:03:14 +00002809 ParmTSI,
2810 Attr.getAttributeSpellingListIndex()));
Joey Goulyaba589c2013-03-08 09:42:32 +00002811}
2812
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002813SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
Michael Han99315932013-01-24 16:46:58 +00002814 StringRef Name,
2815 unsigned AttrSpellingListIndex) {
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002816 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2817 if (ExistingAttr->getName() == Name)
Craig Topperc3ec1492014-05-26 06:22:03 +00002818 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002819 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2820 Diag(Range.getBegin(), diag::note_previous_attribute);
Craig Topperc3ec1492014-05-26 06:22:03 +00002821 return nullptr;
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002822 }
Michael Han99315932013-01-24 16:46:58 +00002823 return ::new (Context) SectionAttr(Range, Context, Name,
2824 AttrSpellingListIndex);
Rafael Espindola9869c3a2012-05-13 02:42:42 +00002825}
2826
Reid Kleckner2a133222015-03-04 23:39:17 +00002827bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2828 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2829 if (!Error.empty()) {
2830 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2831 return false;
2832 }
2833 return true;
2834}
2835
Chandler Carruthedc2c642011-07-02 00:01:44 +00002836static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Daniel Dunbar648bf782009-02-12 17:28:23 +00002837 // Make sure that there is a string literal as the sections's single
2838 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002839 StringRef Str;
2840 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00002841 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
Daniel Dunbar648bf782009-02-12 17:28:23 +00002842 return;
Mike Stump11289f42009-09-09 15:08:12 +00002843
Reid Kleckner2a133222015-03-04 23:39:17 +00002844 if (!S.checkSectionName(LiteralLoc, Str))
2845 return;
2846
Chris Lattner30ba6742009-08-10 19:03:04 +00002847 // If the target wants to validate the section specifier, make it happen.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002848 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
Chris Lattner20aee9b2010-01-12 20:58:53 +00002849 if (!Error.empty()) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002850 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
Chris Lattner20aee9b2010-01-12 20:58:53 +00002851 << Error;
Chris Lattner30ba6742009-08-10 19:03:04 +00002852 return;
2853 }
Mike Stump11289f42009-09-09 15:08:12 +00002854
Michael Han99315932013-01-24 16:46:58 +00002855 unsigned Index = Attr.getAttributeSpellingListIndex();
Benjamin Kramer6ee15622013-09-13 15:35:43 +00002856 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
Rafael Espindolae200f1c2012-05-13 03:25:18 +00002857 if (NewAttr)
2858 D->addAttr(NewAttr);
Daniel Dunbar648bf782009-02-12 17:28:23 +00002859}
2860
Eric Christopher789a7ad2015-06-12 01:36:05 +00002861// Check for things we'd like to warn about, no errors or validation for now.
2862// TODO: Validation should use a backend target library that specifies
2863// the allowable subtarget features and cpus. We could use something like a
2864// TargetCodeGenInfo hook here to do validation.
2865void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2866 for (auto Str : {"tune=", "fpmath="})
2867 if (AttrStr.find(Str) != StringRef::npos)
2868 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2869}
2870
Eric Christopher11acf732015-06-12 01:35:52 +00002871static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Eric Christopher11acf732015-06-12 01:35:52 +00002872 StringRef Str;
2873 SourceLocation LiteralLoc;
2874 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2875 return;
Eric Christopher789a7ad2015-06-12 01:36:05 +00002876 S.checkTargetAttr(LiteralLoc, Str);
Eric Christopher11acf732015-06-12 01:35:52 +00002877 unsigned Index = Attr.getAttributeSpellingListIndex();
2878 TargetAttr *NewAttr =
2879 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2880 D->addAttr(NewAttr);
2881}
2882
Chandler Carruthedc2c642011-07-02 00:01:44 +00002883static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00002884 VarDecl *VD = cast<VarDecl>(D);
2885 if (!VD->hasLocalStorage()) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002886 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00002887 return;
2888 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002889
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002890 Expr *E = Attr.getArgAsExpr(0);
2891 SourceLocation Loc = E->getExprLoc();
Craig Topperc3ec1492014-05-26 06:22:03 +00002892 FunctionDecl *FD = nullptr;
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002893 DeclarationNameInfo NI;
Aaron Ballman00e99962013-08-31 01:11:41 +00002894
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002895 // gcc only allows for simple identifiers. Since we support more than gcc, we
2896 // will warn the user.
2897 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2898 if (DRE->hasQualifier())
2899 S.Diag(Loc, diag::warn_cleanup_ext);
2900 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2901 NI = DRE->getNameInfo();
2902 if (!FD) {
2903 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2904 << NI.getName();
2905 return;
2906 }
2907 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2908 if (ULE->hasExplicitTemplateArgs())
2909 S.Diag(Loc, diag::warn_cleanup_ext);
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002910 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2911 NI = ULE->getNameInfo();
Alp Toker67b47ac2013-10-20 18:48:56 +00002912 if (!FD) {
2913 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2914 << NI.getName();
2915 if (ULE->getType() == S.Context.OverloadTy)
2916 S.NoteAllOverloadCandidates(ULE);
2917 return;
2918 }
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002919 } else {
2920 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
Anders Carlssond277d792009-01-31 01:16:18 +00002921 return;
2922 }
2923
Anders Carlssond277d792009-01-31 01:16:18 +00002924 if (FD->getNumParams() != 1) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002925 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2926 << NI.getName();
Anders Carlssond277d792009-01-31 01:16:18 +00002927 return;
2928 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002929
Anders Carlsson723f55d2009-02-07 23:16:50 +00002930 // We're currently more strict than GCC about what function types we accept.
2931 // If this ever proves to be a problem it should be easy to fix.
2932 QualType Ty = S.Context.getPointerType(VD->getType());
2933 QualType ParamTy = FD->getParamDecl(0)->getType();
Douglas Gregorc03a1082011-01-28 02:26:04 +00002934 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2935 ParamTy, Ty) != Sema::Compatible) {
Aaron Ballmanc12aaff2013-09-11 01:37:41 +00002936 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2937 << NI.getName() << ParamTy << Ty;
Anders Carlsson723f55d2009-02-07 23:16:50 +00002938 return;
2939 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00002940
Michael Han99315932013-01-24 16:46:58 +00002941 D->addAttr(::new (S.Context)
2942 CleanupAttr(Attr.getRange(), S.Context, FD,
2943 Attr.getAttributeSpellingListIndex()));
Anders Carlssond277d792009-01-31 01:16:18 +00002944}
2945
Akira Hatanaka3c268af2017-03-21 02:23:00 +00002946static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
2947 const AttributeList &Attr) {
2948 if (!Attr.isArgIdent(0)) {
2949 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2950 << Attr.getName() << 0 << AANT_ArgumentIdentifier;
2951 return;
2952 }
2953
2954 EnumExtensibilityAttr::Kind ExtensibilityKind;
2955 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2956 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
2957 ExtensibilityKind)) {
2958 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2959 << Attr.getName() << II;
2960 return;
2961 }
2962
2963 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
2964 Attr.getRange(), S.Context, ExtensibilityKind,
2965 Attr.getAttributeSpellingListIndex()));
2966}
2967
Mike Stumpd3bb5572009-07-24 19:02:52 +00002968/// Handle __attribute__((format_arg((idx)))) attribute based on
Bill Wendling44426052012-12-20 19:22:21 +00002969/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00002970static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00002971 Expr *IdxExpr = Attr.getArgAsExpr(0);
Alp Toker601b22c2014-01-21 23:35:24 +00002972 uint64_t Idx;
2973 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002974 return;
Chandler Carruth743682b2010-11-16 08:35:43 +00002975
Eric Christopherb64963e2015-08-13 21:34:35 +00002976 // Make sure the format string is really a string.
Alp Toker601b22c2014-01-21 23:35:24 +00002977 QualType Ty = getFunctionOrMethodParamType(D, Idx);
Mike Stumpd3bb5572009-07-24 19:02:52 +00002978
Eric Christopherb64963e2015-08-13 21:34:35 +00002979 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
2980 if (NotNSStringTy &&
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002981 !isCFStringType(Ty, S.Context) &&
2982 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002983 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002984 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00002985 << "a string type" << IdxExpr->getSourceRange()
2986 << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002987 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002988 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00002989 Ty = getFunctionOrMethodResultType(D);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002990 if (!isNSStringType(Ty, S.Context) &&
2991 !isCFStringType(Ty, S.Context) &&
2992 (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002993 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002994 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
Eric Christopherb64963e2015-08-13 21:34:35 +00002995 << (NotNSStringTy ? "string type" : "NSString")
Aaron Ballman2f9e88b2014-08-04 15:17:29 +00002996 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00002997 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00002998 }
2999
Alp Toker601b22c2014-01-21 23:35:24 +00003000 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003001 // because that has corrected for the implicit this parameter, and is zero-
3002 // based. The attribute expects what the user wrote explicitly.
3003 llvm::APSInt Val;
3004 IdxExpr->EvaluateAsInt(Val, S.Context);
3005
Michael Han99315932013-01-24 16:46:58 +00003006 D->addAttr(::new (S.Context)
Aaron Ballmanbe50eb82013-07-30 00:48:57 +00003007 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
Michael Han99315932013-01-24 16:46:58 +00003008 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianf1c25022009-05-20 17:41:43 +00003009}
3010
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003011enum FormatAttrKind {
3012 CFStringFormat,
3013 NSStringFormat,
3014 StrftimeFormat,
3015 SupportedFormat,
Chris Lattner12161d32010-03-22 21:08:50 +00003016 IgnoredFormat,
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003017 InvalidFormat
3018};
3019
3020/// getFormatAttrKind - Map from format attribute names to supported format
3021/// types.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003022static FormatAttrKind getFormatAttrKind(StringRef Format) {
Benjamin Kramer96a44b62012-05-16 12:44:25 +00003023 return llvm::StringSwitch<FormatAttrKind>(Format)
Mehdi Amini06d367c2016-10-24 20:39:34 +00003024 // Check for formats that get handled specially.
3025 .Case("NSString", NSStringFormat)
3026 .Case("CFString", CFStringFormat)
3027 .Case("strftime", StrftimeFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003028
Mehdi Amini06d367c2016-10-24 20:39:34 +00003029 // Otherwise, check for supported formats.
3030 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3031 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3032 .Case("kprintf", SupportedFormat) // OpenBSD.
3033 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3034 .Case("os_trace", SupportedFormat)
3035 .Case("os_log", SupportedFormat)
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003036
Mehdi Amini06d367c2016-10-24 20:39:34 +00003037 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3038 .Default(InvalidFormat);
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003039}
3040
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003041/// Handle __attribute__((init_priority(priority))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003042/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003043static void handleInitPriorityAttr(Sema &S, Decl *D,
3044 const AttributeList &Attr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003045 if (!S.getLangOpts().CPlusPlus) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003046 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3047 return;
3048 }
3049
Aaron Ballman4a611152013-11-27 16:34:09 +00003050 if (S.getCurFunctionOrMethodDecl()) {
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003051 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3052 Attr.setInvalid();
3053 return;
3054 }
Aaron Ballman4a611152013-11-27 16:34:09 +00003055 QualType T = cast<VarDecl>(D)->getType();
Fariborz Jahanian0bf5ee72010-06-18 23:14:53 +00003056 if (S.Context.getAsArrayType(T))
3057 T = S.Context.getBaseElementType(T);
3058 if (!T->getAs<RecordType>()) {
3059 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3060 Attr.setInvalid();
3061 return;
3062 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003063
3064 Expr *E = Attr.getArgAsExpr(0);
3065 uint32_t prioritynum;
3066 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003067 Attr.setInvalid();
3068 return;
3069 }
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003070
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003071 if (prioritynum < 101 || prioritynum > 65535) {
3072 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003073 << E->getSourceRange() << Attr.getName() << 101 << 65535;
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003074 Attr.setInvalid();
3075 return;
3076 }
Michael Han99315932013-01-24 16:46:58 +00003077 D->addAttr(::new (S.Context)
3078 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3079 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanianef5f6212010-06-18 21:44:06 +00003080}
3081
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003082FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3083 IdentifierInfo *Format, int FormatIdx,
3084 int FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003085 unsigned AttrSpellingListIndex) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003086 // Check whether we already have an equivalent format attribute.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003087 for (auto *F : D->specific_attrs<FormatAttr>()) {
3088 if (F->getType() == Format &&
3089 F->getFormatIdx() == FormatIdx &&
3090 F->getFirstArg() == FirstArg) {
Rafael Espindola92d49452012-05-11 00:36:07 +00003091 // If we don't have a valid location for this attribute, adopt the
3092 // location.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003093 if (F->getLocation().isInvalid())
3094 F->setRange(Range);
Craig Topperc3ec1492014-05-26 06:22:03 +00003095 return nullptr;
Rafael Espindola92d49452012-05-11 00:36:07 +00003096 }
3097 }
3098
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003099 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3100 FirstArg, AttrSpellingListIndex);
Rafael Espindola92d49452012-05-11 00:36:07 +00003101}
3102
Mike Stumpd3bb5572009-07-24 19:02:52 +00003103/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
Bill Wendling44426052012-12-20 19:22:21 +00003104/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
Chandler Carruthedc2c642011-07-02 00:01:44 +00003105static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00003106 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00003107 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman00e99962013-08-31 01:11:41 +00003108 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003109 return;
3110 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003111
Chandler Carruth743682b2010-11-16 08:35:43 +00003112 // In C++ the implicit 'this' function parameter also counts, and they are
3113 // counted from one.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003114 bool HasImplicitThisParam = isInstanceMethod(D);
Alp Toker601b22c2014-01-21 23:35:24 +00003115 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003116
Aaron Ballman00e99962013-08-31 01:11:41 +00003117 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3118 StringRef Format = II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003119
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00003120 if (normalizeName(Format)) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003121 // If we've modified the string name, we need a new identifier for it.
3122 II = &S.Context.Idents.get(Format);
3123 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003124
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003125 // Check for supported formats.
3126 FormatAttrKind Kind = getFormatAttrKind(Format);
Chris Lattner12161d32010-03-22 21:08:50 +00003127
3128 if (Kind == IgnoredFormat)
3129 return;
3130
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003131 if (Kind == InvalidFormat) {
Chris Lattner3b054132008-11-19 05:08:23 +00003132 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
Aaron Ballman190bad42013-12-26 16:13:50 +00003133 << Attr.getName() << II->getName();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003134 return;
3135 }
3136
3137 // checks for the 2nd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003138 Expr *IdxExpr = Attr.getArgAsExpr(1);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003139 uint32_t Idx;
3140 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003141 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003142
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003143 if (Idx < 1 || Idx > NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003144 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003145 << Attr.getName() << 2 << IdxExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003146 return;
3147 }
3148
3149 // FIXME: Do we need to bounds check?
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003150 unsigned ArgIdx = Idx - 1;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003151
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003152 if (HasImplicitThisParam) {
3153 if (ArgIdx == 0) {
Chandler Carruth743682b2010-11-16 08:35:43 +00003154 S.Diag(Attr.getLoc(),
3155 diag::err_format_attribute_implicit_this_format_string)
3156 << IdxExpr->getSourceRange();
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003157 return;
3158 }
3159 ArgIdx--;
3160 }
Mike Stump11289f42009-09-09 15:08:12 +00003161
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003162 // make sure the format string is really a string
Alp Toker601b22c2014-01-21 23:35:24 +00003163 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003164
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003165 if (Kind == CFStringFormat) {
Daniel Dunbar980c6692008-09-26 03:32:58 +00003166 if (!isCFStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003167 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003168 << "a CFString" << IdxExpr->getSourceRange()
3169 << getFunctionOrMethodParamRange(D, ArgIdx);
Daniel Dunbar980c6692008-09-26 03:32:58 +00003170 return;
3171 }
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003172 } else if (Kind == NSStringFormat) {
Mike Stump87c57ac2009-05-16 07:39:55 +00003173 // FIXME: do we need to check if the type is NSString*? What are the
3174 // semantics?
Chris Lattnerb632a6e2008-06-29 00:43:07 +00003175 if (!isNSStringType(Ty, S.Context)) {
Chris Lattner3b054132008-11-19 05:08:23 +00003176 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003177 << "an NSString" << IdxExpr->getSourceRange()
3178 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003179 return;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003180 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003181 } else if (!Ty->isPointerType() ||
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003182 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003183 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
Aaron Ballmandfe8cc52014-08-04 15:26:33 +00003184 << "a string type" << IdxExpr->getSourceRange()
3185 << getFunctionOrMethodParamRange(D, ArgIdx);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003186 return;
3187 }
3188
3189 // check the 3rd argument
Aaron Ballman00e99962013-08-31 01:11:41 +00003190 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003191 uint32_t FirstArg;
3192 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003193 return;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003194
3195 // check if the function is variadic if the 3rd argument non-zero
3196 if (FirstArg != 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003197 if (isFunctionOrMethodVariadic(D)) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003198 ++NumArgs; // +1 for ...
3199 } else {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003200 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003201 return;
3202 }
3203 }
3204
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003205 // strftime requires FirstArg to be 0 because it doesn't read from any
3206 // variable the input is just the current time + the format string.
Daniel Dunbarccbd9a42009-10-18 02:09:17 +00003207 if (Kind == StrftimeFormat) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003208 if (FirstArg != 0) {
Chris Lattner3b054132008-11-19 05:08:23 +00003209 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3210 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003211 return;
3212 }
3213 // if 0 it disables parameter checking (to use with e.g. va_list)
3214 } else if (FirstArg != 0 && FirstArg != NumArgs) {
Chris Lattner3b054132008-11-19 05:08:23 +00003215 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00003216 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003217 return;
3218 }
3219
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003220 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00003221 Idx, FirstArg,
Michael Han99315932013-01-24 16:46:58 +00003222 Attr.getAttributeSpellingListIndex());
Rafael Espindolae200f1c2012-05-13 03:25:18 +00003223 if (NewAttr)
3224 D->addAttr(NewAttr);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003225}
3226
Chandler Carruthedc2c642011-07-02 00:01:44 +00003227static void handleTransparentUnionAttr(Sema &S, Decl *D,
3228 const AttributeList &Attr) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003229 // Try to find the underlying union declaration.
Craig Topperc3ec1492014-05-26 06:22:03 +00003230 RecordDecl *RD = nullptr;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003231 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003232 if (TD && TD->getUnderlyingType()->isUnionType())
3233 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3234 else
Chandler Carruthff4c4f02011-07-01 23:49:12 +00003235 RD = dyn_cast<RecordDecl>(D);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003236
3237 if (!RD || !RD->isUnion()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003238 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
John McCall5fca7ea2011-03-02 12:29:23 +00003239 << Attr.getName() << ExpectedUnion;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003240 return;
3241 }
3242
John McCallf937c022011-10-07 06:10:15 +00003243 if (!RD->isCompleteDefinition()) {
Erich Keane2fe684b2017-02-28 20:44:39 +00003244 if (!RD->isBeingDefined())
3245 S.Diag(Attr.getLoc(),
3246 diag::warn_transparent_union_attribute_not_definition);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003247 return;
3248 }
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003249
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003250 RecordDecl::field_iterator Field = RD->field_begin(),
3251 FieldEnd = RD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003252 if (Field == FieldEnd) {
3253 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3254 return;
3255 }
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003256
David Blaikie40ed2972012-06-06 20:45:41 +00003257 FieldDecl *FirstField = *Field;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003258 QualType FirstType = FirstField->getType();
Douglas Gregor21872662010-06-30 17:24:13 +00003259 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
Mike Stumpd3bb5572009-07-24 19:02:52 +00003260 S.Diag(FirstField->getLocation(),
Douglas Gregor21872662010-06-30 17:24:13 +00003261 diag::warn_transparent_union_attribute_floating)
3262 << FirstType->isVectorType() << FirstType;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003263 return;
3264 }
3265
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003266 if (FirstType->isIncompleteType())
3267 return;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003268 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3269 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3270 for (; Field != FieldEnd; ++Field) {
3271 QualType FieldType = Field->getType();
Alex Lorenz6f4bc4f2016-10-06 09:47:29 +00003272 if (FieldType->isIncompleteType())
3273 return;
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003274 // FIXME: this isn't fully correct; we also need to test whether the
3275 // members of the union would all have the same calling convention as the
3276 // first member of the union. Checking just the size and alignment isn't
3277 // sufficient (consider structs passed on the stack instead of in registers
3278 // as an example).
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003279 if (S.Context.getTypeSize(FieldType) != FirstSize ||
Aaron Ballman54fe5eb2014-01-28 01:47:34 +00003280 S.Context.getTypeAlign(FieldType) > FirstAlign) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003281 // Warn if we drop the attribute.
3282 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003283 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003284 : S.Context.getTypeAlign(FieldType);
Mike Stumpd3bb5572009-07-24 19:02:52 +00003285 S.Diag(Field->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003286 diag::warn_transparent_union_attribute_field_size_align)
3287 << isSize << Field->getDeclName() << FieldBits;
3288 unsigned FirstBits = isSize? FirstSize : FirstAlign;
Mike Stumpd3bb5572009-07-24 19:02:52 +00003289 S.Diag(FirstField->getLocation(),
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003290 diag::note_transparent_union_first_field_size_align)
3291 << isSize << FirstBits;
Eli Friedman7c9ba6a2008-09-02 05:19:23 +00003292 return;
3293 }
3294 }
3295
Michael Han99315932013-01-24 16:46:58 +00003296 RD->addAttr(::new (S.Context)
3297 TransparentUnionAttr(Attr.getRange(), S.Context,
3298 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003299}
3300
Chandler Carruthedc2c642011-07-02 00:01:44 +00003301static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003302 // Make sure that there is a string literal as the annotation's single
3303 // argument.
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003304 StringRef Str;
Tim Northover6a6b63b2013-10-01 14:34:18 +00003305 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003306 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003307
3308 // Don't duplicate annotations that are already set.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003309 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3310 if (I->getAnnotation() == Str)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003311 return;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003312 }
Michael Han99315932013-01-24 16:46:58 +00003313
3314 D->addAttr(::new (S.Context)
Benjamin Kramer6ee15622013-09-13 15:35:43 +00003315 AnnotateAttr(Attr.getRange(), S.Context, Str,
Michael Han99315932013-01-24 16:46:58 +00003316 Attr.getAttributeSpellingListIndex()));
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003317}
3318
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003319static void handleAlignValueAttr(Sema &S, Decl *D,
3320 const AttributeList &Attr) {
3321 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3322 Attr.getAttributeSpellingListIndex());
3323}
3324
3325void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3326 unsigned SpellingListIndex) {
3327 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3328 SourceLocation AttrLoc = AttrRange.getBegin();
3329
3330 QualType T;
3331 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3332 T = TD->getUnderlyingType();
3333 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3334 T = VD->getType();
3335 else
3336 llvm_unreachable("Unknown decl type for align_value");
3337
3338 if (!T->isDependentType() && !T->isAnyPointerType() &&
3339 !T->isReferenceType() && !T->isMemberPointerType()) {
3340 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3341 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3342 return;
3343 }
3344
3345 if (!E->isValueDependent()) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003346 llvm::APSInt Alignment;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003347 ExprResult ICE
3348 = VerifyIntegerConstantExpression(E, &Alignment,
3349 diag::err_align_value_attribute_argument_not_int,
3350 /*AllowFold*/ false);
3351 if (ICE.isInvalid())
3352 return;
3353
3354 if (!Alignment.isPowerOf2()) {
3355 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3356 << E->getSourceRange();
3357 return;
3358 }
3359
3360 D->addAttr(::new (Context)
3361 AlignValueAttr(AttrRange, Context, ICE.get(),
3362 SpellingListIndex));
3363 return;
3364 }
3365
3366 // Save dependent expressions in the AST to be instantiated.
3367 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
Hal Finkel1b0d24e2014-10-02 21:21:25 +00003368}
3369
Chandler Carruthedc2c642011-07-02 00:01:44 +00003370static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003371 // check the attribute arguments.
Chris Lattner4a927cb2008-06-28 23:36:30 +00003372 if (Attr.getNumArgs() > 1) {
Aaron Ballmanb7243382013-07-23 19:30:11 +00003373 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3374 << Attr.getName() << 1;
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003375 return;
3376 }
Aaron Ballman478faed2012-06-19 22:09:27 +00003377
Richard Smith848e1f12013-02-01 08:12:08 +00003378 if (Attr.getNumArgs() == 0) {
3379 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
Craig Topperc3ec1492014-05-26 06:22:03 +00003380 true, nullptr, Attr.getAttributeSpellingListIndex()));
Richard Smith848e1f12013-02-01 08:12:08 +00003381 return;
3382 }
3383
Aaron Ballman00e99962013-08-31 01:11:41 +00003384 Expr *E = Attr.getArgAsExpr(0);
Richard Smith44c247f2013-02-22 08:32:16 +00003385 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3386 S.Diag(Attr.getEllipsisLoc(),
3387 diag::err_pack_expansion_without_parameter_packs);
3388 return;
3389 }
3390
3391 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3392 return;
3393
David Majnemer26a1e0e2015-04-07 02:37:09 +00003394 if (E->isValueDependent()) {
3395 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3396 if (!TND->getUnderlyingType()->isDependentType()) {
3397 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3398 << E->getSourceRange();
3399 return;
3400 }
3401 }
3402 }
3403
Richard Smith44c247f2013-02-22 08:32:16 +00003404 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3405 Attr.isPackExpansion());
Richard Smith848e1f12013-02-01 08:12:08 +00003406}
3407
3408void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
Richard Smith44c247f2013-02-22 08:32:16 +00003409 unsigned SpellingListIndex, bool IsPackExpansion) {
Richard Smith848e1f12013-02-01 08:12:08 +00003410 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3411 SourceLocation AttrLoc = AttrRange.getBegin();
3412
Richard Smith1dba27c2013-01-29 09:02:09 +00003413 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
Richard Smith848e1f12013-02-01 08:12:08 +00003414 if (TmpAttr.isAlignas()) {
Richard Smith1dba27c2013-01-29 09:02:09 +00003415 // C++11 [dcl.align]p1:
3416 // An alignment-specifier may be applied to a variable or to a class
3417 // data member, but it shall not be applied to a bit-field, a function
3418 // parameter, the formal parameter of a catch clause, or a variable
3419 // declared with the register storage class specifier. An
3420 // alignment-specifier may also be applied to the declaration of a class
3421 // or enumeration type.
3422 // C11 6.7.5/2:
3423 // An alignment attribute shall not be specified in a declaration of
3424 // a typedef, or a bit-field, or a function, or a parameter, or an
3425 // object declared with the register storage-class specifier.
3426 int DiagKind = -1;
3427 if (isa<ParmVarDecl>(D)) {
3428 DiagKind = 0;
3429 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3430 if (VD->getStorageClass() == SC_Register)
3431 DiagKind = 1;
3432 if (VD->isExceptionVariable())
3433 DiagKind = 2;
3434 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3435 if (FD->isBitField())
3436 DiagKind = 3;
3437 } else if (!isa<TagDecl>(D)) {
Aaron Ballman3d216a52014-01-02 23:39:11 +00003438 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
Richard Smith9eaab4b2013-02-01 08:25:07 +00003439 << (TmpAttr.isC11() ? ExpectedVariableOrField
3440 : ExpectedVariableFieldOrTag);
Richard Smith1dba27c2013-01-29 09:02:09 +00003441 return;
3442 }
3443 if (DiagKind != -1) {
Richard Smith848e1f12013-02-01 08:12:08 +00003444 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
Aaron Ballman3d216a52014-01-02 23:39:11 +00003445 << &TmpAttr << DiagKind;
Richard Smith1dba27c2013-01-29 09:02:09 +00003446 return;
3447 }
3448 }
3449
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003450 if (E->isTypeDependent() || E->isValueDependent()) {
3451 // Save dependent expressions in the AST to be instantiated.
Richard Smith44c247f2013-02-22 08:32:16 +00003452 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3453 AA->setPackExpansion(IsPackExpansion);
3454 D->addAttr(AA);
Chandler Carruthf40c42f2010-06-25 03:22:07 +00003455 return;
3456 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003457
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003458 // FIXME: Cache the number on the Attr object?
David Majnemer0be6bd02015-07-26 09:02:21 +00003459 llvm::APSInt Alignment;
Douglas Gregore2b37442012-05-04 22:38:52 +00003460 ExprResult ICE
3461 = VerifyIntegerConstantExpression(E, &Alignment,
3462 diag::err_aligned_attribute_argument_not_int,
3463 /*AllowFold*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00003464 if (ICE.isInvalid())
Chris Lattner4627b742008-06-28 23:50:44 +00003465 return;
Richard Smith848e1f12013-02-01 08:12:08 +00003466
David Majnemer0be6bd02015-07-26 09:02:21 +00003467 uint64_t AlignVal = Alignment.getZExtValue();
3468
Richard Smith848e1f12013-02-01 08:12:08 +00003469 // C++11 [dcl.align]p2:
3470 // -- if the constant expression evaluates to zero, the alignment
3471 // specifier shall have no effect
3472 // C11 6.7.5p6:
3473 // An alignment specification of zero has no effect.
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003474 if (!(TmpAttr.isAlignas() && !Alignment)) {
David Majnemer0be6bd02015-07-26 09:02:21 +00003475 if (!llvm::isPowerOf2_64(AlignVal)) {
Paul Robinsond30e2ee2015-07-14 20:52:32 +00003476 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3477 << E->getSourceRange();
3478 return;
3479 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003480 }
Michael Hanaf02bbe2013-02-01 01:19:17 +00003481
David Majnemerabecae72014-02-12 20:36:10 +00003482 // Alignment calculations can wrap around if it's greater than 2**28.
David Majnemer29c69db2015-07-26 01:48:59 +00003483 unsigned MaxValidAlignment =
3484 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3485 : 268435456;
David Majnemer0be6bd02015-07-26 09:02:21 +00003486 if (AlignVal > MaxValidAlignment) {
David Majnemerabecae72014-02-12 20:36:10 +00003487 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3488 << E->getSourceRange();
3489 return;
Aaron Ballman478faed2012-06-19 22:09:27 +00003490 }
Daniel Dunbar6e8c07d2009-02-16 23:37:57 +00003491
David Majnemer0be6bd02015-07-26 09:02:21 +00003492 if (Context.getTargetInfo().isTLSSupported()) {
3493 unsigned MaxTLSAlign =
3494 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3495 .getQuantity();
3496 auto *VD = dyn_cast<VarDecl>(D);
3497 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3498 VD->getTLSKind() != VarDecl::TLS_None) {
3499 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3500 << (unsigned)AlignVal << VD << MaxTLSAlign;
3501 return;
3502 }
3503 }
3504
Richard Smith44c247f2013-02-22 08:32:16 +00003505 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003506 ICE.get(), SpellingListIndex);
Richard Smith44c247f2013-02-22 08:32:16 +00003507 AA->setPackExpansion(IsPackExpansion);
3508 D->addAttr(AA);
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003509}
3510
Michael Hanaf02bbe2013-02-01 01:19:17 +00003511void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
Richard Smith44c247f2013-02-22 08:32:16 +00003512 unsigned SpellingListIndex, bool IsPackExpansion) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003513 // FIXME: Cache the number on the Attr object if non-dependent?
3514 // FIXME: Perform checking of type validity
Richard Smith44c247f2013-02-22 08:32:16 +00003515 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3516 SpellingListIndex);
3517 AA->setPackExpansion(IsPackExpansion);
3518 D->addAttr(AA);
Chris Lattner2c6fcf52008-06-26 18:38:35 +00003519}
Chris Lattneracbc2d22008-06-27 22:18:37 +00003520
Richard Smith848e1f12013-02-01 08:12:08 +00003521void Sema::CheckAlignasUnderalignment(Decl *D) {
3522 assert(D->hasAttrs() && "no attributes on decl");
3523
David Majnemer475b25e2015-01-21 10:54:38 +00003524 QualType UnderlyingTy, DiagTy;
3525 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3526 UnderlyingTy = DiagTy = VD->getType();
3527 } else {
3528 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3529 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3530 UnderlyingTy = ED->getIntegerType();
3531 }
3532 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
Richard Smith848e1f12013-02-01 08:12:08 +00003533 return;
3534
3535 // C++11 [dcl.align]p5, C11 6.7.5/4:
3536 // The combined effect of all alignment attributes in a declaration shall
3537 // not specify an alignment that is less strict than the alignment that
3538 // would otherwise be required for the entity being declared.
Craig Topperc3ec1492014-05-26 06:22:03 +00003539 AlignedAttr *AlignasAttr = nullptr;
Richard Smith848e1f12013-02-01 08:12:08 +00003540 unsigned Align = 0;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003541 for (auto *I : D->specific_attrs<AlignedAttr>()) {
Richard Smith848e1f12013-02-01 08:12:08 +00003542 if (I->isAlignmentDependent())
3543 return;
3544 if (I->isAlignas())
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003545 AlignasAttr = I;
Richard Smith848e1f12013-02-01 08:12:08 +00003546 Align = std::max(Align, I->getAlignment(Context));
3547 }
3548
3549 if (AlignasAttr && Align) {
3550 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
David Majnemer475b25e2015-01-21 10:54:38 +00003551 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
Richard Smith848e1f12013-02-01 08:12:08 +00003552 if (NaturalAlign > RequestedAlign)
3553 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
David Majnemer475b25e2015-01-21 10:54:38 +00003554 << DiagTy << (unsigned)NaturalAlign.getQuantity();
Richard Smith848e1f12013-02-01 08:12:08 +00003555 }
3556}
3557
David Majnemer2c4e00a2014-01-29 22:07:36 +00003558bool Sema::checkMSInheritanceAttrOnDefinition(
David Majnemer4bb09802014-02-10 19:50:15 +00003559 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00003560 MSInheritanceAttr::Spelling SemanticSpelling) {
3561 assert(RD->hasDefinition() && "RD has no definition!");
3562
David Majnemer98c9ee22014-02-07 00:43:07 +00003563 // We may not have seen base specifiers or any virtual methods yet. We will
3564 // have to wait until the record is defined to catch any mismatches.
3565 if (!RD->getDefinition()->isCompleteDefinition())
3566 return false;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003567
David Majnemer98c9ee22014-02-07 00:43:07 +00003568 // The unspecified model never matches what a definition could need.
3569 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3570 return false;
3571
David Majnemer4bb09802014-02-10 19:50:15 +00003572 if (BestCase) {
3573 if (RD->calculateInheritanceModel() == SemanticSpelling)
3574 return false;
3575 } else {
3576 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3577 return false;
3578 }
David Majnemer98c9ee22014-02-07 00:43:07 +00003579
3580 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3581 << 0 /*definition*/;
3582 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3583 << RD->getNameAsString();
3584 return true;
David Majnemer2c4e00a2014-01-29 22:07:36 +00003585}
3586
Alexey Bataevf278eb12015-11-19 10:13:11 +00003587/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3588/// attribute.
3589static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3590 bool &IntegerMode, bool &ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003591 IntegerMode = true;
3592 ComplexMode = false;
Daniel Dunbarafff4342009-10-18 02:09:24 +00003593 switch (Str.size()) {
Chris Lattneracbc2d22008-06-27 22:18:37 +00003594 case 2:
Eli Friedman4735374e2009-03-03 06:41:03 +00003595 switch (Str[0]) {
Alexey Bataevf278eb12015-11-19 10:13:11 +00003596 case 'Q':
3597 DestWidth = 8;
3598 break;
3599 case 'H':
3600 DestWidth = 16;
3601 break;
3602 case 'S':
3603 DestWidth = 32;
3604 break;
3605 case 'D':
3606 DestWidth = 64;
3607 break;
3608 case 'X':
3609 DestWidth = 96;
3610 break;
3611 case 'T':
3612 DestWidth = 128;
3613 break;
Eli Friedman4735374e2009-03-03 06:41:03 +00003614 }
3615 if (Str[1] == 'F') {
3616 IntegerMode = false;
3617 } else if (Str[1] == 'C') {
3618 IntegerMode = false;
3619 ComplexMode = true;
3620 } else if (Str[1] != 'I') {
3621 DestWidth = 0;
3622 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003623 break;
3624 case 4:
3625 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3626 // pointer on PIC16 and other embedded platforms.
Daniel Dunbarafff4342009-10-18 02:09:24 +00003627 if (Str == "word")
Reid Klecknerf27e7522016-02-01 18:58:24 +00003628 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
Daniel Dunbarafff4342009-10-18 02:09:24 +00003629 else if (Str == "byte")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003630 DestWidth = S.Context.getTargetInfo().getCharWidth();
Chris Lattneracbc2d22008-06-27 22:18:37 +00003631 break;
3632 case 7:
Daniel Dunbarafff4342009-10-18 02:09:24 +00003633 if (Str == "pointer")
Douglas Gregore8bbc122011-09-02 00:18:52 +00003634 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
Chris Lattneracbc2d22008-06-27 22:18:37 +00003635 break;
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003636 case 11:
3637 if (Str == "unwind_word")
Rafael Espindola03705972013-01-07 20:01:57 +00003638 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
Rafael Espindolaf0dafd32013-01-07 19:58:54 +00003639 break;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003640 }
Alexey Bataevf278eb12015-11-19 10:13:11 +00003641}
3642
3643/// handleModeAttr - This attribute modifies the width of a decl with primitive
3644/// type.
3645///
3646/// Despite what would be logical, the mode attribute is a decl attribute, not a
3647/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3648/// HImode, not an intermediate pointer.
3649static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3650 // This attribute isn't documented, but glibc uses it. It changes
3651 // the width of an int or unsigned int to the specified size.
3652 if (!Attr.isArgIdent(0)) {
3653 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3654 << AANT_ArgumentIdentifier;
3655 return;
3656 }
3657
3658 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003659
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003660 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3661}
3662
3663void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3664 unsigned SpellingListIndex, bool InInstantiation) {
3665 StringRef Str = Name->getName();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003666 normalizeName(Str);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003667 SourceLocation AttrLoc = AttrRange.getBegin();
Alexey Bataevf278eb12015-11-19 10:13:11 +00003668
3669 unsigned DestWidth = 0;
3670 bool IntegerMode = true;
3671 bool ComplexMode = false;
3672 llvm::APInt VectorSize(64, 0);
3673 if (Str.size() >= 4 && Str[0] == 'V') {
3674 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3675 size_t StrSize = Str.size();
3676 size_t VectorStringLength = 0;
3677 while ((VectorStringLength + 1) < StrSize &&
3678 isdigit(Str[VectorStringLength + 1]))
3679 ++VectorStringLength;
3680 if (VectorStringLength &&
3681 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3682 VectorSize.isPowerOf2()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003683 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
Alexey Bataevf278eb12015-11-19 10:13:11 +00003684 IntegerMode, ComplexMode);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003685 // Avoid duplicate warning from template instantiation.
3686 if (!InInstantiation)
3687 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003688 } else {
3689 VectorSize = 0;
3690 }
3691 }
3692
3693 if (!VectorSize)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003694 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3695
3696 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3697 // and friends, at least with glibc.
3698 // FIXME: Make sure floating-point mappings are accurate
3699 // FIXME: Support XF and TF types
3700 if (!DestWidth) {
3701 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3702 return;
3703 }
Chris Lattneracbc2d22008-06-27 22:18:37 +00003704
3705 QualType OldTy;
Richard Smithdda56e42011-04-15 14:24:37 +00003706 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
Chris Lattneracbc2d22008-06-27 22:18:37 +00003707 OldTy = TD->getUnderlyingType();
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003708 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3709 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3710 // Try to get type from enum declaration, default to int.
3711 OldTy = ED->getIntegerType();
3712 if (OldTy.isNull())
3713 OldTy = Context.IntTy;
3714 } else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003715 OldTy = cast<ValueDecl>(D)->getType();
Eli Friedman4735374e2009-03-03 06:41:03 +00003716
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003717 if (OldTy->isDependentType()) {
3718 D->addAttr(::new (Context)
3719 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3720 return;
3721 }
3722
Alexey Bataev326057d2015-06-19 07:46:21 +00003723 // Base type can also be a vector type (see PR17453).
3724 // Distinguish between base type and base element type.
3725 QualType OldElemTy = OldTy;
3726 if (const VectorType *VT = OldTy->getAs<VectorType>())
3727 OldElemTy = VT->getElementType();
3728
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003729 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3730 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3731 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3732 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3733 VectorSize.getBoolValue()) {
3734 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3735 return;
3736 }
3737 bool IntegralOrAnyEnumType =
3738 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3739
3740 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3741 !IntegralOrAnyEnumType)
3742 Diag(AttrLoc, diag::err_mode_not_primitive);
Eli Friedman4735374e2009-03-03 06:41:03 +00003743 else if (IntegerMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003744 if (!IntegralOrAnyEnumType)
3745 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003746 } else if (ComplexMode) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003747 if (!OldElemTy->isComplexType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003748 Diag(AttrLoc, diag::err_mode_wrong_type);
Eli Friedman4735374e2009-03-03 06:41:03 +00003749 } else {
Alexey Bataev326057d2015-06-19 07:46:21 +00003750 if (!OldElemTy->isFloatingType())
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003751 Diag(AttrLoc, diag::err_mode_wrong_type);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003752 }
3753
Alexey Bataev326057d2015-06-19 07:46:21 +00003754 QualType NewElemTy;
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003755
3756 if (IntegerMode)
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003757 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3758 OldElemTy->isSignedIntegerType());
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003759 else
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003760 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
Stepan Dyatkovskiyb88c30f2013-09-18 09:08:52 +00003761
Alexey Bataev326057d2015-06-19 07:46:21 +00003762 if (NewElemTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003763 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003764 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003765 }
3766
Eli Friedman4735374e2009-03-03 06:41:03 +00003767 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003768 NewElemTy = Context.getComplexType(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003769 }
3770
3771 QualType NewTy = NewElemTy;
Alexey Bataevf278eb12015-11-19 10:13:11 +00003772 if (VectorSize.getBoolValue()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003773 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3774 VectorType::GenericVector);
Alexey Bataevf278eb12015-11-19 10:13:11 +00003775 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
Alexey Bataev326057d2015-06-19 07:46:21 +00003776 // Complex machine mode does not support base vector types.
3777 if (ComplexMode) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003778 Diag(AttrLoc, diag::err_complex_mode_vector_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003779 return;
3780 }
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003781 unsigned NumElements = Context.getTypeSize(OldElemTy) *
Alexey Bataev326057d2015-06-19 07:46:21 +00003782 OldVT->getNumElements() /
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003783 Context.getTypeSize(NewElemTy);
Alexey Bataev326057d2015-06-19 07:46:21 +00003784 NewTy =
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003785 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
Alexey Bataev326057d2015-06-19 07:46:21 +00003786 }
3787
3788 if (NewTy.isNull()) {
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003789 Diag(AttrLoc, diag::err_mode_wrong_type);
Alexey Bataev326057d2015-06-19 07:46:21 +00003790 return;
Chris Lattneracbc2d22008-06-27 22:18:37 +00003791 }
3792
3793 // Install the new type.
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003794 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3795 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003796 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3797 ED->setIntegerType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003798 else
Aaron Ballman6c8848a2016-01-19 22:54:26 +00003799 cast<ValueDecl>(D)->setType(NewTy);
Enea Zaffanellaa86d88c2013-06-20 12:46:19 +00003800
Denis Zobnind9e2dcd2016-02-02 13:50:39 +00003801 D->addAttr(::new (Context)
3802 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
Chris Lattneracbc2d22008-06-27 22:18:37 +00003803}
Chris Lattner9e2aafe2008-06-29 00:23:49 +00003804
Chandler Carruthedc2c642011-07-02 00:01:44 +00003805static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Michael Han99315932013-01-24 16:46:58 +00003806 D->addAttr(::new (S.Context)
3807 NoDebugAttr(Attr.getRange(), S.Context,
3808 Attr.getAttributeSpellingListIndex()));
Anders Carlsson76187b42009-02-13 06:46:13 +00003809}
3810
Paul Robinson30e41fb2014-12-15 18:57:28 +00003811AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
Paul Robinson080b1f32015-01-13 18:34:56 +00003812 IdentifierInfo *Ident,
Paul Robinson30e41fb2014-12-15 18:57:28 +00003813 unsigned AttrSpellingListIndex) {
3814 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
Paul Robinson080b1f32015-01-13 18:34:56 +00003815 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
Paul Robinson30e41fb2014-12-15 18:57:28 +00003816 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3817 return nullptr;
3818 }
3819
3820 if (D->hasAttr<AlwaysInlineAttr>())
3821 return nullptr;
3822
3823 return ::new (Context) AlwaysInlineAttr(Range, Context,
3824 AttrSpellingListIndex);
3825}
3826
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00003827CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3828 IdentifierInfo *Ident,
3829 unsigned AttrSpellingListIndex) {
3830 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3831 return nullptr;
3832
3833 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3834}
3835
3836InternalLinkageAttr *
3837Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3838 IdentifierInfo *Ident,
3839 unsigned AttrSpellingListIndex) {
3840 if (auto VD = dyn_cast<VarDecl>(D)) {
3841 // Attribute applies to Var but not any subclass of it (like ParmVar,
3842 // ImplicitParm or VarTemplateSpecialization).
3843 if (VD->getKind() != Decl::Var) {
3844 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3845 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3846 : ExpectedVariableOrFunction);
3847 return nullptr;
3848 }
3849 // Attribute does not apply to non-static local variables.
3850 if (VD->hasLocalStorage()) {
3851 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3852 return nullptr;
3853 }
3854 }
3855
3856 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3857 return nullptr;
3858
3859 return ::new (Context)
3860 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3861}
3862
Paul Robinson30e41fb2014-12-15 18:57:28 +00003863MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3864 unsigned AttrSpellingListIndex) {
3865 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3866 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3867 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3868 return nullptr;
3869 }
3870
3871 if (D->hasAttr<MinSizeAttr>())
3872 return nullptr;
3873
3874 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3875}
3876
3877OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3878 unsigned AttrSpellingListIndex) {
3879 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3880 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3881 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3882 D->dropAttr<AlwaysInlineAttr>();
3883 }
3884 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3885 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3886 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3887 D->dropAttr<MinSizeAttr>();
3888 }
3889
3890 if (D->hasAttr<OptimizeNoneAttr>())
3891 return nullptr;
3892
3893 return ::new (Context) OptimizeNoneAttr(Range, Context,
3894 AttrSpellingListIndex);
3895}
3896
Paul Robinsonf0674352014-03-31 22:29:15 +00003897static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3898 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00003899 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
Charles Davis0e379112016-08-08 21:19:08 +00003900 Attr.getName()))
Akira Hatanakac8667622015-11-06 23:56:15 +00003901 return;
3902
Paul Robinson080b1f32015-01-13 18:34:56 +00003903 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3904 D, Attr.getRange(), Attr.getName(),
3905 Attr.getAttributeSpellingListIndex()))
3906 D->addAttr(Inline);
Paul Robinsonf0674352014-03-31 22:29:15 +00003907}
3908
Paul Robinson080b1f32015-01-13 18:34:56 +00003909static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3910 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3911 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3912 D->addAttr(MinSize);
Paul Robinsonaae2fba2014-12-10 23:34:36 +00003913}
3914
Paul Robinsonf0674352014-03-31 22:29:15 +00003915static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3916 const AttributeList &Attr) {
Paul Robinson080b1f32015-01-13 18:34:56 +00003917 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3918 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3919 D->addAttr(Optnone);
Paul Robinsonf0674352014-03-31 22:29:15 +00003920}
3921
Justin Lebare71b2fa2016-09-30 23:57:34 +00003922static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3923 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
3924 Attr.getName()))
3925 return;
3926 auto *VD = cast<VarDecl>(D);
3927 if (!VD->hasGlobalStorage()) {
3928 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
3929 return;
3930 }
3931 D->addAttr(::new (S.Context) CUDAConstantAttr(
3932 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3933}
3934
Justin Lebar10411012016-09-30 23:57:30 +00003935static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3936 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
3937 Attr.getName()))
3938 return;
3939 auto *VD = cast<VarDecl>(D);
Justin Lebar281ce2a2016-10-02 15:24:50 +00003940 // extern __shared__ is only allowed on arrays with no length (e.g.
3941 // "int x[]").
3942 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
Justin Lebar10411012016-09-30 23:57:30 +00003943 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
3944 return;
3945 }
Justin Lebaraa370bd2016-10-13 18:45:13 +00003946 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
3947 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
3948 << S.CurrentCUDATarget())
3949 return;
Justin Lebar10411012016-09-30 23:57:30 +00003950 D->addAttr(::new (S.Context) CUDASharedAttr(
3951 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3952}
3953
Chandler Carruthedc2c642011-07-02 00:01:44 +00003954static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Justin Lebar3eaaf862016-01-13 01:07:35 +00003955 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
3956 Attr.getName()) ||
3957 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
3958 Attr.getName())) {
3959 return;
3960 }
Aaron Ballman3aff6332013-12-02 19:30:36 +00003961 FunctionDecl *FD = cast<FunctionDecl>(D);
Alp Toker314cc812014-01-25 16:55:45 +00003962 if (!FD->getReturnType()->isVoidType()) {
Alp Tokerf5b10792014-07-02 12:55:58 +00003963 SourceRange RTRange = FD->getReturnTypeSourceRange();
3964 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
Aaron Ballman3aff6332013-12-02 19:30:36 +00003965 << FD->getType()
Alp Tokerf5b10792014-07-02 12:55:58 +00003966 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3967 : FixItHint());
Aaron Ballman3aff6332013-12-02 19:30:36 +00003968 return;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003969 }
Justin Lebarc66a1062016-01-20 00:26:57 +00003970 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
3971 if (Method->isInstance()) {
3972 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
3973 << Method;
3974 return;
3975 }
3976 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
3977 }
3978 // Only warn for "inline" when compiling for host, to cut down on noise.
3979 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
3980 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003981
Aaron Ballman3aff6332013-12-02 19:30:36 +00003982 D->addAttr(::new (S.Context)
3983 CUDAGlobalAttr(Attr.getRange(), S.Context,
Eli Bendersky83860042014-09-02 22:00:06 +00003984 Attr.getAttributeSpellingListIndex()));
Peter Collingbourne6ab610c2010-12-01 03:15:31 +00003985}
3986
Chandler Carruthedc2c642011-07-02 00:01:44 +00003987static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00003988 FunctionDecl *Fn = cast<FunctionDecl>(D);
Douglas Gregor35b57532009-10-27 21:01:01 +00003989 if (!Fn->isInlineSpecified()) {
Chris Lattnerddf6ca02009-04-20 19:12:28 +00003990 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
Chris Lattner4225e232009-04-14 17:02:11 +00003991 return;
3992 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00003993
Michael Han99315932013-01-24 16:46:58 +00003994 D->addAttr(::new (S.Context)
3995 GNUInlineAttr(Attr.getRange(), S.Context,
3996 Attr.getAttributeSpellingListIndex()));
Chris Lattnereaad6b72009-04-14 16:30:50 +00003997}
3998
Chandler Carruthedc2c642011-07-02 00:01:44 +00003999static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004000 if (hasDeclarator(D)) return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004001
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004002 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
John McCall3882ace2011-01-05 12:14:39 +00004003 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4004 CallingConv CC;
Richard Smitheec7cb12015-05-28 23:38:53 +00004005 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
John McCall3882ace2011-01-05 12:14:39 +00004006 return;
4007
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004008 if (!isa<ObjCMethodDecl>(D)) {
4009 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4010 << Attr.getName() << ExpectedFunctionOrMethod;
John McCall3882ace2011-01-05 12:14:39 +00004011 return;
4012 }
4013
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004014 switch (Attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004015 case AttributeList::AT_FastCall:
Michael Han99315932013-01-24 16:46:58 +00004016 D->addAttr(::new (S.Context)
4017 FastCallAttr(Attr.getRange(), S.Context,
4018 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004019 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004020 case AttributeList::AT_StdCall:
Michael Han99315932013-01-24 16:46:58 +00004021 D->addAttr(::new (S.Context)
4022 StdCallAttr(Attr.getRange(), S.Context,
4023 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004024 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004025 case AttributeList::AT_ThisCall:
Michael Han99315932013-01-24 16:46:58 +00004026 D->addAttr(::new (S.Context)
4027 ThisCallAttr(Attr.getRange(), S.Context,
4028 Attr.getAttributeSpellingListIndex()));
Douglas Gregor4d13d102010-08-30 23:30:49 +00004029 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004030 case AttributeList::AT_CDecl:
Michael Han99315932013-01-24 16:46:58 +00004031 D->addAttr(::new (S.Context)
4032 CDeclAttr(Attr.getRange(), S.Context,
4033 Attr.getAttributeSpellingListIndex()));
Abramo Bagnara50099372010-04-30 13:10:51 +00004034 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004035 case AttributeList::AT_Pascal:
Michael Han99315932013-01-24 16:46:58 +00004036 D->addAttr(::new (S.Context)
4037 PascalAttr(Attr.getRange(), S.Context,
4038 Attr.getAttributeSpellingListIndex()));
Dawn Perchik335e16b2010-09-03 01:29:35 +00004039 return;
John McCall477f2bb2016-03-03 06:39:32 +00004040 case AttributeList::AT_SwiftCall:
4041 D->addAttr(::new (S.Context)
4042 SwiftCallAttr(Attr.getRange(), S.Context,
4043 Attr.getAttributeSpellingListIndex()));
4044 return;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004045 case AttributeList::AT_VectorCall:
4046 D->addAttr(::new (S.Context)
4047 VectorCallAttr(Attr.getRange(), S.Context,
4048 Attr.getAttributeSpellingListIndex()));
4049 return;
Charles Davisb5a214e2013-08-30 04:39:01 +00004050 case AttributeList::AT_MSABI:
4051 D->addAttr(::new (S.Context)
4052 MSABIAttr(Attr.getRange(), S.Context,
4053 Attr.getAttributeSpellingListIndex()));
4054 return;
4055 case AttributeList::AT_SysVABI:
4056 D->addAttr(::new (S.Context)
4057 SysVABIAttr(Attr.getRange(), S.Context,
4058 Attr.getAttributeSpellingListIndex()));
4059 return;
Erich Keane757d3172016-11-02 18:29:35 +00004060 case AttributeList::AT_RegCall:
4061 D->addAttr(::new (S.Context) RegCallAttr(
4062 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4063 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004064 case AttributeList::AT_Pcs: {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004065 PcsAttr::PCSType PCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004066 switch (CC) {
4067 case CC_AAPCS:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004068 PCS = PcsAttr::AAPCS;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004069 break;
4070 case CC_AAPCS_VFP:
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004071 PCS = PcsAttr::AAPCS_VFP;
Benjamin Kramer25885f42012-08-14 13:24:39 +00004072 break;
4073 default:
4074 llvm_unreachable("unexpected calling convention in pcs attribute");
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004075 }
4076
Michael Han99315932013-01-24 16:46:58 +00004077 D->addAttr(::new (S.Context)
4078 PcsAttr(Attr.getRange(), S.Context, PCS,
4079 Attr.getAttributeSpellingListIndex()));
Derek Schuffa2020962012-10-16 22:30:41 +00004080 return;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004081 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004082 case AttributeList::AT_IntelOclBicc:
Michael Han99315932013-01-24 16:46:58 +00004083 D->addAttr(::new (S.Context)
4084 IntelOclBiccAttr(Attr.getRange(), S.Context,
4085 Attr.getAttributeSpellingListIndex()));
Guy Benyeif0a014b2012-12-25 08:53:55 +00004086 return;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004087 case AttributeList::AT_PreserveMost:
4088 D->addAttr(::new (S.Context) PreserveMostAttr(
4089 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4090 return;
4091 case AttributeList::AT_PreserveAll:
4092 D->addAttr(::new (S.Context) PreserveAllAttr(
4093 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4094 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00004095 default:
4096 llvm_unreachable("unexpected attribute kind");
Abramo Bagnara50099372010-04-30 13:10:51 +00004097 }
4098}
4099
Matthias Gehre01a63382017-03-27 19:45:24 +00004100static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4101 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4102 return;
4103
4104 std::vector<StringRef> DiagnosticIdentifiers;
4105 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4106 StringRef RuleName;
4107
4108 if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4109 return;
4110
4111 // FIXME: Warn if the rule name is unknown. This is tricky because only
4112 // clang-tidy knows about available rules.
4113 DiagnosticIdentifiers.push_back(RuleName);
4114 }
4115 D->addAttr(::new (S.Context) SuppressAttr(
4116 Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4117 DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4118}
4119
Aaron Ballman02df2e02012-12-09 17:45:41 +00004120bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
4121 const FunctionDecl *FD) {
John McCall3882ace2011-01-05 12:14:39 +00004122 if (attr.isInvalid())
4123 return true;
4124
John McCall3b5a8f52016-03-03 00:10:03 +00004125 if (attr.hasProcessingCache()) {
4126 CC = (CallingConv) attr.getProcessingCache();
4127 return false;
4128 }
4129
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004130 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
Aaron Ballman00e99962013-08-31 01:11:41 +00004131 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
John McCall3882ace2011-01-05 12:14:39 +00004132 attr.setInvalid();
4133 return true;
4134 }
4135
Aaron Ballmanab7691c2014-01-09 22:48:32 +00004136 // TODO: diagnose uses of these conventions on the wrong target.
John McCall3882ace2011-01-05 12:14:39 +00004137 switch (attr.getKind()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004138 case AttributeList::AT_CDecl: CC = CC_C; break;
4139 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4140 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4141 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4142 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
John McCall477f2bb2016-03-03 06:39:32 +00004143 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
Reid Klecknerd7857f02014-10-24 17:42:17 +00004144 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
Erich Keane757d3172016-11-02 18:29:35 +00004145 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
Charles Davisb5a214e2013-08-30 04:39:01 +00004146 case AttributeList::AT_MSABI:
4147 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4148 CC_X86_64Win64;
4149 break;
4150 case AttributeList::AT_SysVABI:
4151 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4152 CC_C;
4153 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004154 case AttributeList::AT_Pcs: {
Aaron Ballmand6600a52013-09-13 17:48:25 +00004155 StringRef StrRef;
Tim Northover6a6b63b2013-10-01 14:34:18 +00004156 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004157 attr.setInvalid();
4158 return true;
4159 }
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004160 if (StrRef == "aapcs") {
4161 CC = CC_AAPCS;
4162 break;
4163 } else if (StrRef == "aapcs-vfp") {
4164 CC = CC_AAPCS_VFP;
4165 break;
4166 }
Benjamin Kramer833fb9f2012-08-14 13:13:47 +00004167
4168 attr.setInvalid();
4169 Diag(attr.getLoc(), diag::err_invalid_pcs);
4170 return true;
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004171 }
Guy Benyeif0a014b2012-12-25 08:53:55 +00004172 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00004173 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4174 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
David Blaikie8a40f702012-01-17 06:56:22 +00004175 default: llvm_unreachable("unexpected attribute kind");
John McCall3882ace2011-01-05 12:14:39 +00004176 }
4177
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004178 const TargetInfo &TI = Context.getTargetInfo();
4179 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004180 if (A != TargetInfo::CCCR_OK) {
4181 if (A == TargetInfo::CCCR_Warning)
4182 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
Aaron Ballman02df2e02012-12-09 17:45:41 +00004183
Reid Kleckner9fde2e02015-02-26 19:43:46 +00004184 // This convention is not valid for the target. Use the default function or
4185 // method calling convention.
Alexey Bataeva7547182016-05-18 09:06:38 +00004186 bool IsCXXMethod = false, IsVariadic = false;
4187 if (FD) {
4188 IsCXXMethod = FD->isCXXInstanceMember();
4189 IsVariadic = FD->isVariadic();
4190 }
4191 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
Aaron Ballmane91c6be2012-10-02 14:26:08 +00004192 }
4193
John McCall3b5a8f52016-03-03 00:10:03 +00004194 attr.setProcessingCache((unsigned) CC);
John McCall3882ace2011-01-05 12:14:39 +00004195 return false;
4196}
4197
John McCall477f2bb2016-03-03 06:39:32 +00004198/// Pointer-like types in the default address space.
4199static bool isValidSwiftContextType(QualType type) {
4200 if (!type->hasPointerRepresentation())
4201 return type->isDependentType();
4202 return type->getPointeeType().getAddressSpace() == 0;
4203}
4204
4205/// Pointers and references in the default address space.
4206static bool isValidSwiftIndirectResultType(QualType type) {
4207 if (auto ptrType = type->getAs<PointerType>()) {
4208 type = ptrType->getPointeeType();
4209 } else if (auto refType = type->getAs<ReferenceType>()) {
4210 type = refType->getPointeeType();
4211 } else {
4212 return type->isDependentType();
4213 }
4214 return type.getAddressSpace() == 0;
4215}
4216
4217/// Pointers and references to pointers in the default address space.
4218static bool isValidSwiftErrorResultType(QualType type) {
4219 if (auto ptrType = type->getAs<PointerType>()) {
4220 type = ptrType->getPointeeType();
4221 } else if (auto refType = type->getAs<ReferenceType>()) {
4222 type = refType->getPointeeType();
4223 } else {
4224 return type->isDependentType();
4225 }
4226 if (!type.getQualifiers().empty())
4227 return false;
4228 return isValidSwiftContextType(type);
4229}
4230
4231static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4232 ParameterABI abi) {
4233 S.AddParameterABIAttr(attr.getRange(), D, abi,
4234 attr.getAttributeSpellingListIndex());
4235}
4236
4237void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4238 unsigned spellingIndex) {
4239
4240 QualType type = cast<ParmVarDecl>(D)->getType();
4241
4242 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4243 if (existingAttr->getABI() != abi) {
4244 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4245 << getParameterABISpelling(abi) << existingAttr;
4246 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4247 return;
4248 }
4249 }
4250
4251 switch (abi) {
4252 case ParameterABI::Ordinary:
4253 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4254
4255 case ParameterABI::SwiftContext:
4256 if (!isValidSwiftContextType(type)) {
4257 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4258 << getParameterABISpelling(abi)
4259 << /*pointer to pointer */ 0 << type;
4260 }
4261 D->addAttr(::new (Context)
4262 SwiftContextAttr(range, Context, spellingIndex));
4263 return;
4264
4265 case ParameterABI::SwiftErrorResult:
4266 if (!isValidSwiftErrorResultType(type)) {
4267 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4268 << getParameterABISpelling(abi)
4269 << /*pointer to pointer */ 1 << type;
4270 }
4271 D->addAttr(::new (Context)
4272 SwiftErrorResultAttr(range, Context, spellingIndex));
4273 return;
4274
4275 case ParameterABI::SwiftIndirectResult:
4276 if (!isValidSwiftIndirectResultType(type)) {
4277 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4278 << getParameterABISpelling(abi)
4279 << /*pointer*/ 0 << type;
4280 }
4281 D->addAttr(::new (Context)
4282 SwiftIndirectResultAttr(range, Context, spellingIndex));
4283 return;
4284 }
4285 llvm_unreachable("bad parameter ABI attribute");
4286}
4287
John McCall3882ace2011-01-05 12:14:39 +00004288/// Checks a regparm attribute, returning true if it is ill-formed and
4289/// otherwise setting numParams to the appropriate value.
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004290bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4291 if (Attr.isInvalid())
John McCall3882ace2011-01-05 12:14:39 +00004292 return true;
4293
Aaron Ballmanc2cbc662013-07-18 18:01:48 +00004294 if (!checkAttributeNumArgs(*this, Attr, 1)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004295 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004296 return true;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004297 }
Eli Friedman7044b762009-03-27 21:06:47 +00004298
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004299 uint32_t NP;
Aaron Ballman00e99962013-08-31 01:11:41 +00004300 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004301 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004302 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004303 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004304 }
4305
Douglas Gregore8bbc122011-09-02 00:18:52 +00004306 if (Context.getTargetInfo().getRegParmMax() == 0) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004307 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
Eli Friedman7044b762009-03-27 21:06:47 +00004308 << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004309 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004310 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004311 }
4312
Aaron Ballmanf22ef5a2013-11-21 01:50:40 +00004313 numParams = NP;
Douglas Gregore8bbc122011-09-02 00:18:52 +00004314 if (numParams > Context.getTargetInfo().getRegParmMax()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004315 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
Douglas Gregore8bbc122011-09-02 00:18:52 +00004316 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004317 Attr.setInvalid();
John McCall3882ace2011-01-05 12:14:39 +00004318 return true;
Eli Friedman7044b762009-03-27 21:06:47 +00004319 }
4320
John McCall3882ace2011-01-05 12:14:39 +00004321 return false;
Fariborz Jahaniana2d609e2009-03-27 18:38:55 +00004322}
4323
Artem Belevichbcec9da2016-06-06 22:54:57 +00004324// Checks whether an argument of launch_bounds attribute is
4325// acceptable, performs implicit conversion to Rvalue, and returns
4326// non-nullptr Expr result on success. Otherwise, it returns nullptr
4327// and may output an error.
4328static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4329 const CUDALaunchBoundsAttr &Attr,
4330 const unsigned Idx) {
Artem Belevich7093e402015-04-21 22:55:54 +00004331 if (S.DiagnoseUnexpandedParameterPack(E))
Artem Belevichbcec9da2016-06-06 22:54:57 +00004332 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004333
4334 // Accept template arguments for now as they depend on something else.
4335 // We'll get to check them when they eventually get instantiated.
4336 if (E->isValueDependent())
Artem Belevichbcec9da2016-06-06 22:54:57 +00004337 return E;
Artem Belevich7093e402015-04-21 22:55:54 +00004338
4339 llvm::APSInt I(64);
4340 if (!E->isIntegerConstantExpr(I, S.Context)) {
4341 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4342 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
Artem Belevichbcec9da2016-06-06 22:54:57 +00004343 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004344 }
4345 // Make sure we can fit it in 32 bits.
4346 if (!I.isIntN(32)) {
4347 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4348 << 32 << /* Unsigned */ 1;
Artem Belevichbcec9da2016-06-06 22:54:57 +00004349 return nullptr;
Artem Belevich7093e402015-04-21 22:55:54 +00004350 }
4351 if (I < 0)
4352 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4353 << &Attr << Idx << E->getSourceRange();
4354
Artem Belevichbcec9da2016-06-06 22:54:57 +00004355 // We may need to perform implicit conversion of the argument.
4356 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4357 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4358 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4359 assert(!ValArg.isInvalid() &&
4360 "Unexpected PerformCopyInitialization() failure.");
4361
4362 return ValArg.getAs<Expr>();
Artem Belevich7093e402015-04-21 22:55:54 +00004363}
4364
4365void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4366 Expr *MinBlocks, unsigned SpellingListIndex) {
4367 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4368 SpellingListIndex);
Artem Belevichbcec9da2016-06-06 22:54:57 +00004369 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4370 if (MaxThreads == nullptr)
Aaron Ballman3aff6332013-12-02 19:30:36 +00004371 return;
4372
Artem Belevichbcec9da2016-06-06 22:54:57 +00004373 if (MinBlocks) {
4374 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4375 if (MinBlocks == nullptr)
4376 return;
4377 }
Artem Belevich7093e402015-04-21 22:55:54 +00004378
4379 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4380 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4381}
4382
4383static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4384 const AttributeList &Attr) {
4385 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4386 !checkAttributeAtMostNumArgs(S, Attr, 2))
4387 return;
4388
4389 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4390 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4391 Attr.getAttributeSpellingListIndex());
Peter Collingbourne827301e2010-12-12 23:03:07 +00004392}
4393
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004394static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4395 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004396 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004397 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004398 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004399 return;
4400 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004401
4402 if (!checkAttributeNumArgs(S, Attr, 3))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004403 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004404
Aaron Ballman00e99962013-08-31 01:11:41 +00004405 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004406
4407 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4408 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4409 << Attr.getName() << ExpectedFunctionOrMethod;
4410 return;
4411 }
4412
4413 uint64_t ArgumentIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004414 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4415 ArgumentIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004416 return;
4417
4418 uint64_t TypeTagIdx;
Alp Toker601b22c2014-01-21 23:35:24 +00004419 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4420 TypeTagIdx))
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004421 return;
4422
Aaron Ballmanfaed0fa2013-12-26 16:30:30 +00004423 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004424 if (IsPointer) {
4425 // Ensure that buffer has a pointer type.
Alp Toker601b22c2014-01-21 23:35:24 +00004426 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004427 if (!BufferTy->isPointerType()) {
4428 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00004429 << Attr.getName() << 0;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004430 }
4431 }
4432
Michael Han99315932013-01-24 16:46:58 +00004433 D->addAttr(::new (S.Context)
4434 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4435 ArgumentIdx, TypeTagIdx, IsPointer,
4436 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004437}
4438
4439static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4440 const AttributeList &Attr) {
Aaron Ballman00e99962013-08-31 01:11:41 +00004441 if (!Attr.isArgIdent(0)) {
Aaron Ballman29982272013-07-23 14:03:57 +00004442 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
Aaron Ballman3bf758c2013-07-30 01:31:03 +00004443 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004444 return;
4445 }
Aaron Ballman00e99962013-08-31 01:11:41 +00004446
4447 if (!checkAttributeNumArgs(S, Attr, 1))
4448 return;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004449
Aaron Ballman90f8c6f2013-11-25 18:50:49 +00004450 if (!isa<VarDecl>(D)) {
4451 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4452 << Attr.getName() << ExpectedVariable;
4453 return;
4454 }
4455
Aaron Ballman00e99962013-08-31 01:11:41 +00004456 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
Craig Topperc3ec1492014-05-26 06:22:03 +00004457 TypeSourceInfo *MatchingCTypeLoc = nullptr;
Richard Smithb87c4652013-10-31 21:23:20 +00004458 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4459 assert(MatchingCTypeLoc && "no type source info for attribute argument");
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004460
Michael Han99315932013-01-24 16:46:58 +00004461 D->addAttr(::new (S.Context)
4462 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
Richard Smithb87c4652013-10-31 21:23:20 +00004463 MatchingCTypeLoc,
Michael Han99315932013-01-24 16:46:58 +00004464 Attr.getLayoutCompatible(),
4465 Attr.getMustBeNull(),
4466 Attr.getAttributeSpellingListIndex()));
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00004467}
4468
Dean Michael Berris418da3f2017-03-06 07:08:21 +00004469static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4470 const AttributeList &Attr) {
4471 uint64_t ArgCount;
4472 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
4473 ArgCount))
4474 return;
4475
4476 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4477 D->addAttr(::new (S.Context)
4478 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4479 Attr.getAttributeSpellingListIndex()));
4480}
4481
Chris Lattner9e2aafe2008-06-29 00:23:49 +00004482//===----------------------------------------------------------------------===//
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004483// Checker-specific attribute handlers.
4484//===----------------------------------------------------------------------===//
4485
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004486static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004487 return type->isDependentType() ||
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004488 type->isObjCRetainableType();
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004489}
4490
John McCalled433932011-01-25 03:31:58 +00004491static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004492 return type->isDependentType() ||
4493 type->isObjCObjectPointerType() ||
4494 S.Context.isObjCNSObjectType(type);
John McCalled433932011-01-25 03:31:58 +00004495}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00004496
John McCalled433932011-01-25 03:31:58 +00004497static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
Douglas Gregorf892c7f2011-10-09 22:26:49 +00004498 return type->isDependentType() ||
4499 type->isPointerType() ||
4500 isValidSubjectOfNSAttribute(S, type);
John McCalled433932011-01-25 03:31:58 +00004501}
4502
Chandler Carruthedc2c642011-07-02 00:01:44 +00004503static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
John McCall3b5a8f52016-03-03 00:10:03 +00004504 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4505 Attr.getKind() == AttributeList::AT_NSConsumed,
4506 /*template instantiation*/ false);
4507}
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004508
John McCall3b5a8f52016-03-03 00:10:03 +00004509void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4510 unsigned spellingIndex, bool isNSConsumed,
4511 bool isTemplateInstantiation) {
4512 ParmVarDecl *param = cast<ParmVarDecl>(D);
4513 bool typeOK;
4514
4515 if (isNSConsumed) {
4516 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004517 } else {
John McCall3b5a8f52016-03-03 00:10:03 +00004518 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
John McCalled433932011-01-25 03:31:58 +00004519 }
4520
4521 if (!typeOK) {
John McCall3b5a8f52016-03-03 00:10:03 +00004522 // These attributes are normally just advisory, but in ARC, ns_consumed
4523 // is significant. Allow non-dependent code to contain inappropriate
4524 // attributes even in ARC, but require template instantiations to be
4525 // set up correctly.
4526 Diag(D->getLocStart(),
4527 (isTemplateInstantiation && isNSConsumed &&
4528 getLangOpts().ObjCAutoRefCount
4529 ? diag::err_ns_attribute_wrong_parameter_type
4530 : diag::warn_ns_attribute_wrong_parameter_type))
4531 << attrRange
4532 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4533 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
John McCalled433932011-01-25 03:31:58 +00004534 return;
4535 }
4536
John McCall3b5a8f52016-03-03 00:10:03 +00004537 if (isNSConsumed)
4538 param->addAttr(::new (Context)
4539 NSConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004540 else
John McCall3b5a8f52016-03-03 00:10:03 +00004541 param->addAttr(::new (Context)
4542 CFConsumedAttr(attrRange, Context, spellingIndex));
John McCalled433932011-01-25 03:31:58 +00004543}
4544
Chandler Carruthedc2c642011-07-02 00:01:44 +00004545static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4546 const AttributeList &Attr) {
John McCalled433932011-01-25 03:31:58 +00004547 QualType returnType;
Mike Stumpd3bb5572009-07-24 19:02:52 +00004548
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004549 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004550 returnType = MD->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00004551 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004552 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
John McCall31168b02011-06-15 23:02:42 +00004553 return; // ignore: was handled as a type attribute
Fariborz Jahanian272b7dc2012-08-28 22:26:21 +00004554 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4555 returnType = PD->getType();
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004556 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004557 returnType = FD->getReturnType();
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004558 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4559 returnType = Param->getType()->getPointeeType();
4560 if (returnType.isNull()) {
4561 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4562 << Attr.getName() << /*pointer-to-CF*/2
4563 << Attr.getRange();
4564 return;
4565 }
4566 } else {
4567 AttributeDeclKind ExpectedDeclKind;
4568 switch (Attr.getKind()) {
4569 default: llvm_unreachable("invalid ownership attribute");
4570 case AttributeList::AT_NSReturnsRetained:
4571 case AttributeList::AT_NSReturnsAutoreleased:
4572 case AttributeList::AT_NSReturnsNotRetained:
4573 ExpectedDeclKind = ExpectedFunctionOrMethod;
4574 break;
4575
4576 case AttributeList::AT_CFReturnsRetained:
4577 case AttributeList::AT_CFReturnsNotRetained:
4578 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4579 break;
4580 }
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004581 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004582 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004583 return;
4584 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004585
John McCalled433932011-01-25 03:31:58 +00004586 bool typeOK;
4587 bool cf;
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004588 switch (Attr.getKind()) {
David Blaikie8a40f702012-01-17 06:56:22 +00004589 default: llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004590 case AttributeList::AT_NSReturnsRetained:
Fariborz Jahanian4eba3dc2014-06-12 16:12:30 +00004591 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
Fariborz Jahanian9c100322014-06-11 21:22:53 +00004592 cf = false;
4593 break;
4594
4595 case AttributeList::AT_NSReturnsAutoreleased:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004596 case AttributeList::AT_NSReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004597 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4598 cf = false;
4599 break;
4600
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004601 case AttributeList::AT_CFReturnsRetained:
4602 case AttributeList::AT_CFReturnsNotRetained:
John McCalled433932011-01-25 03:31:58 +00004603 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4604 cf = true;
4605 break;
4606 }
4607
4608 if (!typeOK) {
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00004609 if (isa<ParmVarDecl>(D)) {
4610 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4611 << Attr.getName() << /*pointer-to-CF*/2
4612 << Attr.getRange();
4613 } else {
4614 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4615 enum : unsigned {
4616 Function,
4617 Method,
4618 Property
4619 } SubjectKind = Function;
4620 if (isa<ObjCMethodDecl>(D))
4621 SubjectKind = Method;
4622 else if (isa<ObjCPropertyDecl>(D))
4623 SubjectKind = Property;
4624 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4625 << Attr.getName() << SubjectKind << cf
4626 << Attr.getRange();
4627 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004628 return;
Ted Kremenek3b204e42009-05-13 21:07:32 +00004629 }
Mike Stumpd3bb5572009-07-24 19:02:52 +00004630
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004631 switch (Attr.getKind()) {
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004632 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004633 llvm_unreachable("invalid ownership attribute");
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004634 case AttributeList::AT_NSReturnsAutoreleased:
Nico Weber462fd1e2015-01-07 23:50:05 +00004635 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4636 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
John McCalled433932011-01-25 03:31:58 +00004637 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004638 case AttributeList::AT_CFReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004639 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4640 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004641 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004642 case AttributeList::AT_NSReturnsNotRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004643 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4644 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenekd9c66632010-02-18 00:05:45 +00004645 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004646 case AttributeList::AT_CFReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004647 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4648 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004649 return;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00004650 case AttributeList::AT_NSReturnsRetained:
Nico Weber462fd1e2015-01-07 23:50:05 +00004651 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4652 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00004653 return;
4654 };
4655}
4656
John McCallcf166702011-07-22 08:53:00 +00004657static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4658 const AttributeList &attr) {
Fariborz Jahanian8bf05562013-09-19 17:52:50 +00004659 const int EP_ObjCMethod = 1;
4660 const int EP_ObjCProperty = 2;
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004661
John McCallcf166702011-07-22 08:53:00 +00004662 SourceLocation loc = attr.getLoc();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004663 QualType resultType;
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004664 if (isa<ObjCMethodDecl>(D))
Alp Toker314cc812014-01-25 16:55:45 +00004665 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004666 else
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004667 resultType = cast<ObjCPropertyDecl>(D)->getType();
John McCallcf166702011-07-22 08:53:00 +00004668
Fariborz Jahanian044a5be2011-09-30 20:50:23 +00004669 if (!resultType->isReferenceType() &&
4670 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
Fariborz Jahanian8a5e9472013-09-19 16:37:20 +00004671 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
John McCallcf166702011-07-22 08:53:00 +00004672 << SourceRange(loc)
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004673 << attr.getName()
4674 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
Fariborz Jahanian5c005832013-09-19 17:18:55 +00004675 << /*non-retainable pointer*/ 2;
John McCallcf166702011-07-22 08:53:00 +00004676
4677 // Drop the attribute.
4678 return;
4679 }
4680
Nico Weber462fd1e2015-01-07 23:50:05 +00004681 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4682 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
John McCallcf166702011-07-22 08:53:00 +00004683}
4684
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004685static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4686 const AttributeList &attr) {
Aaron Ballman74eeeae2013-11-27 13:27:02 +00004687 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004688
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004689 DeclContext *DC = method->getDeclContext();
4690 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4691 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4692 << attr.getName() << 0;
4693 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4694 return;
4695 }
4696 if (method->getMethodFamily() == OMF_dealloc) {
4697 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4698 << attr.getName() << 1;
4699 return;
4700 }
4701
Michael Han99315932013-01-24 16:46:58 +00004702 method->addAttr(::new (S.Context)
4703 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4704 attr.getAttributeSpellingListIndex()));
Fariborz Jahanian566fff02012-09-07 23:46:23 +00004705}
4706
Aaron Ballmanfb763042013-12-02 18:05:46 +00004707static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4708 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004709 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4710 Attr.getName()))
John McCall32f5fe12011-09-30 05:12:12 +00004711 return;
John McCall32f5fe12011-09-30 05:12:12 +00004712
Aaron Ballmanfb763042013-12-02 18:05:46 +00004713 D->addAttr(::new (S.Context)
4714 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4715 Attr.getAttributeSpellingListIndex()));
4716}
4717
4718static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4719 const AttributeList &Attr) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00004720 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4721 Attr.getName()))
Aaron Ballmanfb763042013-12-02 18:05:46 +00004722 return;
4723
4724 D->addAttr(::new (S.Context)
4725 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4726 Attr.getAttributeSpellingListIndex()));
John McCall32f5fe12011-09-30 05:12:12 +00004727}
4728
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004729static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4730 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004731 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004732
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004733 if (!Parm) {
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004734 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004735 return;
4736 }
John McCall28592582015-02-01 22:34:06 +00004737
4738 // Typedefs only allow objc_bridge(id) and have some additional checking.
4739 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4740 if (!Parm->Ident->isStr("id")) {
4741 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4742 << Attr.getName();
4743 return;
4744 }
4745
4746 // Only allow 'cv void *'.
4747 QualType T = TD->getUnderlyingType();
4748 if (!T->isVoidPointerType()) {
4749 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4750 return;
4751 }
4752 }
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004753
4754 D->addAttr(::new (S.Context)
Ted Kremenek2d3379e2013-11-21 07:20:34 +00004755 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00004756 Attr.getAttributeSpellingListIndex()));
4757}
4758
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004759static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4760 const AttributeList &Attr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004761 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4762
Fariborz Jahanian87c77912013-11-21 20:50:32 +00004763 if (!Parm) {
4764 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4765 return;
4766 }
4767
4768 D->addAttr(::new (S.Context)
4769 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4770 Attr.getAttributeSpellingListIndex()));
4771}
4772
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004773static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4774 const AttributeList &Attr) {
4775 IdentifierInfo *RelatedClass =
Craig Topperc3ec1492014-05-26 06:22:03 +00004776 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004777 if (!RelatedClass) {
4778 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4779 return;
4780 }
4781 IdentifierInfo *ClassMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004782 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004783 IdentifierInfo *InstanceMethod =
Craig Topperc3ec1492014-05-26 06:22:03 +00004784 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00004785 D->addAttr(::new (S.Context)
4786 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4787 ClassMethod, InstanceMethod,
4788 Attr.getAttributeSpellingListIndex()));
4789}
4790
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004791static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4792 const AttributeList &Attr) {
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004793 ObjCInterfaceDecl *IFace;
Nico Weber462fd1e2015-01-07 23:50:05 +00004794 if (ObjCCategoryDecl *CatDecl =
4795 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
Fariborz Jahanian6efab6e2014-03-14 18:19:46 +00004796 IFace = CatDecl->getClassInterface();
4797 else
4798 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
Ben Langmuirc91ac9e2015-01-20 20:41:36 +00004799
4800 if (!IFace)
4801 return;
4802
Argyrios Kyrtzidis9ed9e5f2013-12-03 21:11:30 +00004803 IFace->setHasDesignatedInitializers();
Argyrios Kyrtzidise8186812013-12-07 06:08:04 +00004804 D->addAttr(::new (S.Context)
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00004805 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4806 Attr.getAttributeSpellingListIndex()));
4807}
4808
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004809static void handleObjCRuntimeName(Sema &S, Decl *D,
4810 const AttributeList &Attr) {
Fariborz Jahaniana2e5deb2014-07-16 19:44:34 +00004811 StringRef MetaDataName;
4812 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4813 return;
4814 D->addAttr(::new (S.Context)
4815 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4816 MetaDataName,
4817 Attr.getAttributeSpellingListIndex()));
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00004818}
4819
Nico Webera6916892016-06-10 18:53:04 +00004820// When a user wants to use objc_boxable with a union or struct
4821// but they don't have access to the declaration (legacy/third-party code)
4822// then they can 'enable' this feature with a typedef:
Alex Denisovfde64952015-06-26 05:28:36 +00004823// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4824static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4825 bool notify = false;
4826
4827 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4828 if (RD && RD->getDefinition()) {
4829 RD = RD->getDefinition();
4830 notify = true;
4831 }
4832
4833 if (RD) {
4834 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4835 ObjCBoxableAttr(Attr.getRange(), S.Context,
4836 Attr.getAttributeSpellingListIndex());
4837 RD->addAttr(BoxableAttr);
4838 if (notify) {
4839 // we need to notify ASTReader/ASTWriter about
4840 // modification of existing declaration
4841 if (ASTMutationListener *L = S.getASTMutationListener())
4842 L->AddedAttributeToRecord(BoxableAttr, RD);
4843 }
4844 }
4845}
4846
Chandler Carruthedc2c642011-07-02 00:01:44 +00004847static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4848 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004849 if (hasDeclarator(D)) return;
John McCall31168b02011-06-15 23:02:42 +00004850
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004851 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
Douglas Gregor5c3cc422012-03-14 16:55:17 +00004852 << Attr.getRange() << Attr.getName() << ExpectedVariable;
John McCall31168b02011-06-15 23:02:42 +00004853}
4854
Chandler Carruthedc2c642011-07-02 00:01:44 +00004855static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4856 const AttributeList &Attr) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004857 ValueDecl *vd = cast<ValueDecl>(D);
John McCall31168b02011-06-15 23:02:42 +00004858 QualType type = vd->getType();
4859
4860 if (!type->isDependentType() &&
4861 !type->isObjCLifetimeType()) {
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004862 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
John McCall31168b02011-06-15 23:02:42 +00004863 << type;
4864 return;
4865 }
4866
4867 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4868
4869 // If we have no lifetime yet, check the lifetime we're presumably
4870 // going to infer.
4871 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4872 lifetime = type->getObjCARCImplicitLifetime();
4873
4874 switch (lifetime) {
4875 case Qualifiers::OCL_None:
4876 assert(type->isDependentType() &&
4877 "didn't infer lifetime for non-dependent type?");
4878 break;
4879
4880 case Qualifiers::OCL_Weak: // meaningful
4881 case Qualifiers::OCL_Strong: // meaningful
4882 break;
4883
4884 case Qualifiers::OCL_ExplicitNone:
4885 case Qualifiers::OCL_Autoreleasing:
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004886 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
John McCall31168b02011-06-15 23:02:42 +00004887 << (lifetime == Qualifiers::OCL_Autoreleasing);
4888 break;
4889 }
4890
Chandler Carruthff4c4f02011-07-01 23:49:12 +00004891 D->addAttr(::new (S.Context)
Michael Han99315932013-01-24 16:46:58 +00004892 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4893 Attr.getAttributeSpellingListIndex()));
John McCall31168b02011-06-15 23:02:42 +00004894}
4895
Francois Picheta83957a2010-12-19 06:50:37 +00004896//===----------------------------------------------------------------------===//
4897// Microsoft specific attribute handlers.
4898//===----------------------------------------------------------------------===//
4899
Nico Weber88f5ed92016-09-13 18:55:26 +00004900UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4901 unsigned AttrSpellingListIndex, StringRef Uuid) {
4902 if (const auto *UA = D->getAttr<UuidAttr>()) {
Nico Weberd58c2602016-09-14 01:16:54 +00004903 if (UA->getGuid().equals_lower(Uuid))
Nico Weber88f5ed92016-09-13 18:55:26 +00004904 return nullptr;
4905 Diag(UA->getLocation(), diag::err_mismatched_uuid);
4906 Diag(Range.getBegin(), diag::note_previous_uuid);
4907 D->dropAttr<UuidAttr>();
4908 }
4909
4910 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
4911}
4912
Chandler Carruthedc2c642011-07-02 00:01:44 +00004913static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
Aaron Ballmandf8fe4c2013-11-24 21:35:16 +00004914 if (!S.LangOpts.CPlusPlus) {
4915 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4916 << Attr.getName() << AttributeLangSupport::C;
4917 return;
4918 }
4919
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004920 StringRef StrRef;
4921 SourceLocation LiteralLoc;
Tim Northover6a6b63b2013-10-01 14:34:18 +00004922 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
Reid Kleckner140c4a72013-05-17 14:04:52 +00004923 return;
Francois Pichet7da11662010-12-20 01:41:49 +00004924
David Majnemer89085342013-08-09 08:56:20 +00004925 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4926 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
David Majnemer89085342013-08-09 08:56:20 +00004927 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4928 StrRef = StrRef.drop_front().drop_back();
Francois Pichet7da11662010-12-20 01:41:49 +00004929
Reid Kleckner140c4a72013-05-17 14:04:52 +00004930 // Validate GUID length.
David Majnemer89085342013-08-09 08:56:20 +00004931 if (StrRef.size() != 36) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004932 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00004933 return;
4934 }
Anders Carlsson19588aa2011-01-23 21:07:30 +00004935
David Majnemer89085342013-08-09 08:56:20 +00004936 for (unsigned i = 0; i < 36; ++i) {
Reid Kleckner140c4a72013-05-17 14:04:52 +00004937 if (i == 8 || i == 13 || i == 18 || i == 23) {
David Majnemer89085342013-08-09 08:56:20 +00004938 if (StrRef[i] != '-') {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004939 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Francois Pichet7da11662010-12-20 01:41:49 +00004940 return;
4941 }
David Majnemer89085342013-08-09 08:56:20 +00004942 } else if (!isHexDigit(StrRef[i])) {
Benjamin Kramer6ee15622013-09-13 15:35:43 +00004943 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
Reid Kleckner140c4a72013-05-17 14:04:52 +00004944 return;
Francois Pichet7da11662010-12-20 01:41:49 +00004945 }
Reid Kleckner140c4a72013-05-17 14:04:52 +00004946 }
Francois Picheta83957a2010-12-19 06:50:37 +00004947
Nico Weber88f5ed92016-09-13 18:55:26 +00004948 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
4949 Attr.getAttributeSpellingListIndex(), StrRef);
4950 if (UA)
4951 D->addAttr(UA);
Charles Davis163855f2010-02-16 18:27:26 +00004952}
4953
David Majnemer2c4e00a2014-01-29 22:07:36 +00004954static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4955 if (!S.LangOpts.CPlusPlus) {
4956 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4957 << Attr.getName() << AttributeLangSupport::C;
4958 return;
4959 }
4960 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
David Majnemer4bb09802014-02-10 19:50:15 +00004961 D, Attr.getRange(), /*BestCase=*/true,
4962 Attr.getAttributeSpellingListIndex(),
David Majnemer2c4e00a2014-01-29 22:07:36 +00004963 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
David Majnemer929025d2016-01-26 19:30:26 +00004964 if (IA) {
David Majnemer2c4e00a2014-01-29 22:07:36 +00004965 D->addAttr(IA);
David Majnemer929025d2016-01-26 19:30:26 +00004966 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
4967 }
David Majnemer2c4e00a2014-01-29 22:07:36 +00004968}
4969
Reid Kleckner7d6d2702014-05-01 03:16:47 +00004970static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4971 const AttributeList &Attr) {
4972 VarDecl *VD = cast<VarDecl>(D);
4973 if (!S.Context.getTargetInfo().isTLSSupported()) {
4974 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4975 return;
4976 }
4977 if (VD->getTSCSpec() != TSCS_unspecified) {
4978 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4979 return;
4980 }
4981 if (VD->hasLocalStorage()) {
4982 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4983 return;
4984 }
4985 VD->addAttr(::new (S.Context) ThreadAttr(
4986 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4987}
4988
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00004989static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4990 SmallVector<StringRef, 4> Tags;
4991 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4992 StringRef Tag;
4993 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
4994 return;
4995 Tags.push_back(Tag);
4996 }
4997
4998 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
4999 if (!NS->isInline()) {
5000 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5001 return;
5002 }
5003 if (NS->isAnonymousNamespace()) {
5004 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5005 return;
5006 }
5007 if (Attr.getNumArgs() == 0)
5008 Tags.push_back(NS->getName());
5009 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5010 return;
5011
5012 // Store tags sorted and without duplicates.
5013 std::sort(Tags.begin(), Tags.end());
5014 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5015
5016 D->addAttr(::new (S.Context)
5017 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5018 Attr.getAttributeSpellingListIndex()));
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00005019}
5020
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005021static void handleARMInterruptAttr(Sema &S, Decl *D,
5022 const AttributeList &Attr) {
5023 // Check the attribute arguments.
5024 if (Attr.getNumArgs() > 1) {
5025 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5026 << Attr.getName() << 1;
5027 return;
5028 }
5029
5030 StringRef Str;
5031 SourceLocation ArgLoc;
5032
5033 if (Attr.getNumArgs() == 0)
5034 Str = "";
5035 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5036 return;
5037
5038 ARMInterruptAttr::InterruptType Kind;
5039 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5040 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5041 << Attr.getName() << Str << ArgLoc;
5042 return;
5043 }
5044
5045 unsigned Index = Attr.getAttributeSpellingListIndex();
5046 D->addAttr(::new (S.Context)
5047 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5048}
5049
5050static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5051 const AttributeList &Attr) {
5052 if (!checkAttributeNumArgs(S, Attr, 1))
5053 return;
5054
5055 if (!Attr.isArgExpr(0)) {
5056 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5057 << AANT_ArgumentIntegerConstant;
5058 return;
5059 }
5060
5061 // FIXME: Check for decl - it should be void ()(void).
5062
5063 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5064 llvm::APSInt NumParams(32);
5065 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5066 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5067 << Attr.getName() << AANT_ArgumentIntegerConstant
5068 << NumParamsExpr->getSourceRange();
5069 return;
5070 }
5071
5072 unsigned Num = NumParams.getLimitedValue(255);
5073 if ((Num & 1) || Num > 30) {
5074 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5075 << Attr.getName() << (int)NumParams.getSExtValue()
5076 << NumParamsExpr->getSourceRange();
5077 return;
5078 }
5079
Aaron Ballman36a53502014-01-16 13:03:14 +00005080 D->addAttr(::new (S.Context)
5081 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5082 Attr.getAttributeSpellingListIndex()));
5083 D->addAttr(UsedAttr::CreateImplicit(S.Context));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005084}
5085
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005086static void handleMipsInterruptAttr(Sema &S, Decl *D,
5087 const AttributeList &Attr) {
5088 // Only one optional argument permitted.
5089 if (Attr.getNumArgs() > 1) {
5090 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5091 << Attr.getName() << 1;
5092 return;
5093 }
5094
5095 StringRef Str;
5096 SourceLocation ArgLoc;
5097
5098 if (Attr.getNumArgs() == 0)
5099 Str = "";
5100 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5101 return;
5102
5103 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5104 // a) Must be a function.
5105 // b) Must have no parameters.
5106 // c) Must have the 'void' return type.
5107 // d) Cannot have the 'mips16' attribute, as that instruction set
5108 // lacks the 'eret' instruction.
5109 // e) The attribute itself must either have no argument or one of the
5110 // valid interrupt types, see [MipsInterruptDocs].
5111
5112 if (!isFunctionOrMethod(D)) {
5113 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5114 << "'interrupt'" << ExpectedFunctionOrMethod;
5115 return;
5116 }
5117
5118 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5119 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5120 << 0;
5121 return;
5122 }
5123
5124 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5125 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5126 << 1;
5127 return;
5128 }
5129
5130 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5131 Attr.getName()))
5132 return;
5133
5134 MipsInterruptAttr::InterruptType Kind;
5135 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5136 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5137 << Attr.getName() << "'" + std::string(Str) + "'";
5138 return;
5139 }
5140
5141 D->addAttr(::new (S.Context) MipsInterruptAttr(
5142 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5143}
5144
Alexey Bataevd51e9932016-01-15 04:06:31 +00005145static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5146 const AttributeList &Attr) {
5147 // Semantic checks for a function with the 'interrupt' attribute.
5148 // a) Must be a function.
5149 // b) Must have the 'void' return type.
5150 // c) Must take 1 or 2 arguments.
5151 // d) The 1st argument must be a pointer.
5152 // e) The 2nd argument (if any) must be an unsigned integer.
5153 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5154 CXXMethodDecl::isStaticOverloadedOperator(
5155 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5156 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5157 << Attr.getName() << ExpectedFunctionWithProtoType;
5158 return;
5159 }
5160 // Interrupt handler must have void return type.
5161 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5162 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5163 diag::err_anyx86_interrupt_attribute)
5164 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5165 ? 0
5166 : 1)
5167 << 0;
5168 return;
5169 }
5170 // Interrupt handler must have 1 or 2 parameters.
5171 unsigned NumParams = getFunctionOrMethodNumParams(D);
5172 if (NumParams < 1 || NumParams > 2) {
5173 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5174 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5175 ? 0
5176 : 1)
5177 << 1;
5178 return;
5179 }
5180 // The first argument must be a pointer.
5181 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5182 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5183 diag::err_anyx86_interrupt_attribute)
5184 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5185 ? 0
5186 : 1)
5187 << 2;
5188 return;
5189 }
5190 // The second argument, if present, must be an unsigned integer.
5191 unsigned TypeSize =
5192 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5193 ? 64
5194 : 32;
5195 if (NumParams == 2 &&
5196 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5197 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5198 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5199 diag::err_anyx86_interrupt_attribute)
5200 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5201 ? 0
5202 : 1)
5203 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5204 return;
5205 }
5206 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5207 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5208 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5209}
5210
Dylan McKaye8232d72017-02-08 05:09:26 +00005211static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5212 if (!isFunctionOrMethod(D)) {
5213 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5214 << "'interrupt'" << ExpectedFunction;
5215 return;
5216 }
5217
5218 if (!checkAttributeNumArgs(S, Attr, 0))
5219 return;
5220
5221 handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5222}
5223
5224static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5225 if (!isFunctionOrMethod(D)) {
5226 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5227 << "'signal'" << ExpectedFunction;
5228 return;
5229 }
5230
5231 if (!checkAttributeNumArgs(S, Attr, 0))
5232 return;
5233
5234 handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5235}
5236
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005237static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5238 // Dispatch the interrupt attribute based on the current target.
Alexey Bataevd51e9932016-01-15 04:06:31 +00005239 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5240 case llvm::Triple::msp430:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005241 handleMSP430InterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005242 break;
5243 case llvm::Triple::mipsel:
5244 case llvm::Triple::mips:
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005245 handleMipsInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005246 break;
5247 case llvm::Triple::x86:
5248 case llvm::Triple::x86_64:
5249 handleAnyX86InterruptAttr(S, D, Attr);
5250 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00005251 case llvm::Triple::avr:
5252 handleAVRInterruptAttr(S, D, Attr);
5253 break;
Alexey Bataevd51e9932016-01-15 04:06:31 +00005254 default:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005255 handleARMInterruptAttr(S, D, Attr);
Alexey Bataevd51e9932016-01-15 04:06:31 +00005256 break;
5257 }
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005258}
5259
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005260static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5261 const AttributeList &Attr) {
5262 uint32_t Min = 0;
5263 Expr *MinExpr = Attr.getArgAsExpr(0);
5264 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005265 return;
5266
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005267 uint32_t Max = 0;
5268 Expr *MaxExpr = Attr.getArgAsExpr(1);
5269 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5270 return;
5271
5272 if (Min == 0 && Max != 0) {
5273 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5274 << Attr.getName() << 0;
5275 return;
5276 }
5277 if (Min > Max) {
5278 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5279 << Attr.getName() << 1;
5280 return;
5281 }
5282
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005283 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005284 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5285 Attr.getAttributeSpellingListIndex()));
5286}
5287
5288static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5289 const AttributeList &Attr) {
5290 uint32_t Min = 0;
5291 Expr *MinExpr = Attr.getArgAsExpr(0);
5292 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5293 return;
5294
5295 uint32_t Max = 0;
5296 if (Attr.getNumArgs() == 2) {
5297 Expr *MaxExpr = Attr.getArgAsExpr(1);
5298 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5299 return;
5300 }
5301
5302 if (Min == 0 && Max != 0) {
5303 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5304 << Attr.getName() << 0;
5305 return;
5306 }
5307 if (Max != 0 && Min > Max) {
5308 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5309 << Attr.getName() << 1;
5310 return;
5311 }
5312
5313 D->addAttr(::new (S.Context)
5314 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5315 Attr.getAttributeSpellingListIndex()));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005316}
5317
5318static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5319 const AttributeList &Attr) {
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005320 uint32_t NumSGPR = 0;
5321 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5322 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005323 return;
5324
5325 D->addAttr(::new (S.Context)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005326 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5327 Attr.getAttributeSpellingListIndex()));
5328}
5329
5330static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5331 const AttributeList &Attr) {
5332 uint32_t NumVGPR = 0;
5333 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5334 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5335 return;
5336
5337 D->addAttr(::new (S.Context)
5338 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005339 Attr.getAttributeSpellingListIndex()));
5340}
5341
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005342static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5343 const AttributeList& Attr) {
5344 // If we try to apply it to a function pointer, don't warn, but don't
5345 // do anything, either. It doesn't matter anyway, because there's nothing
5346 // special about calling a force_align_arg_pointer function.
5347 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5348 if (VD && VD->getType()->isFunctionPointerType())
5349 return;
5350 // Also don't warn on function pointer typedefs.
5351 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5352 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5353 TD->getUnderlyingType()->isFunctionType()))
5354 return;
5355 // Attribute can only be applied to function types.
5356 if (!isa<FunctionDecl>(D)) {
5357 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5358 << Attr.getName() << /* function */0;
5359 return;
5360 }
5361
Aaron Ballman36a53502014-01-16 13:03:14 +00005362 D->addAttr(::new (S.Context)
5363 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5364 Attr.getAttributeSpellingListIndex()));
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005365}
5366
David Majnemercd3ebfe2016-05-23 17:16:12 +00005367static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5368 uint32_t Version;
5369 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5370 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5371 return;
5372
5373 // TODO: Investigate what happens with the next major version of MSVC.
5374 if (Version != LangOptions::MSVC2015) {
5375 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5376 << Attr.getName() << Version << VersionExpr->getSourceRange();
5377 return;
5378 }
5379
5380 D->addAttr(::new (S.Context)
5381 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5382 Attr.getAttributeSpellingListIndex()));
5383}
5384
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005385DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5386 unsigned AttrSpellingListIndex) {
5387 if (D->hasAttr<DLLExportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005388 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
Craig Topperc3ec1492014-05-26 06:22:03 +00005389 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005390 }
5391
5392 if (D->hasAttr<DLLImportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005393 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005394
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005395 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005396}
5397
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005398DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5399 unsigned AttrSpellingListIndex) {
5400 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
Nico Rieck60478662014-02-22 19:47:30 +00005401 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005402 D->dropAttr<DLLImportAttr>();
5403 }
5404
5405 if (D->hasAttr<DLLExportAttr>())
Craig Topperc3ec1492014-05-26 06:22:03 +00005406 return nullptr;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005407
Aaron Ballman3f5f3e72014-01-20 16:15:55 +00005408 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005409}
5410
Hans Wennborge82f19c2014-06-24 23:57:05 +00005411static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
Hans Wennborg5e645282014-06-24 23:57:13 +00005412 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5413 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5414 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5415 << A.getName();
5416 return;
5417 }
5418
Hans Wennborg606bd6d2014-11-03 14:24:45 +00005419 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5420 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5421 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5422 // MinGW doesn't allow dllimport on inline functions.
5423 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5424 << A.getName();
5425 return;
5426 }
5427 }
5428
Hans Wennborg5869ec42015-09-15 21:05:30 +00005429 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5430 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5431 MD->getParent()->isLambda()) {
5432 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5433 return;
5434 }
5435 }
5436
Hans Wennborge82f19c2014-06-24 23:57:05 +00005437 unsigned Index = A.getAttributeSpellingListIndex();
5438 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5439 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5440 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005441 if (NewAttr)
5442 D->addAttr(NewAttr);
5443}
5444
David Majnemer2c4e00a2014-01-29 22:07:36 +00005445MSInheritanceAttr *
David Majnemer4bb09802014-02-10 19:50:15 +00005446Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
David Majnemer2c4e00a2014-01-29 22:07:36 +00005447 unsigned AttrSpellingListIndex,
5448 MSInheritanceAttr::Spelling SemanticSpelling) {
5449 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5450 if (IA->getSemanticSpelling() == SemanticSpelling)
Craig Topperc3ec1492014-05-26 06:22:03 +00005451 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005452 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5453 << 1 /*previous declaration*/;
5454 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5455 D->dropAttr<MSInheritanceAttr>();
5456 }
5457
5458 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5459 if (RD->hasDefinition()) {
David Majnemer4bb09802014-02-10 19:50:15 +00005460 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5461 SemanticSpelling)) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005462 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005463 }
5464 } else {
5465 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5466 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5467 << 1 /*partial specialization*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005468 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005469 }
5470 if (RD->getDescribedClassTemplate()) {
5471 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5472 << 0 /*primary template*/;
Craig Topperc3ec1492014-05-26 06:22:03 +00005473 return nullptr;
David Majnemer2c4e00a2014-01-29 22:07:36 +00005474 }
5475 }
5476
5477 return ::new (Context)
David Majnemer4bb09802014-02-10 19:50:15 +00005478 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
David Majnemer2c4e00a2014-01-29 22:07:36 +00005479}
5480
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005481static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5482 // The capability attributes take a single string parameter for the name of
5483 // the capability they represent. The lockable attribute does not take any
5484 // parameters. However, semantically, both attributes represent the same
5485 // concept, and so they use the same semantic attribute. Eventually, the
5486 // lockable attribute will be removed.
Aaron Ballman6c810072014-03-05 21:47:13 +00005487 //
Alp Toker958027b2014-07-14 19:42:55 +00005488 // For backward compatibility, any capability which has no specified string
Aaron Ballman6c810072014-03-05 21:47:13 +00005489 // literal will be considered a "mutex."
5490 StringRef N("mutex");
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005491 SourceLocation LiteralLoc;
5492 if (Attr.getKind() == AttributeList::AT_Capability &&
5493 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5494 return;
5495
Aaron Ballman6c810072014-03-05 21:47:13 +00005496 // Currently, there are only two names allowed for a capability: role and
5497 // mutex (case insensitive). Diagnose other capability names.
5498 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5499 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5500
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005501 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5502 Attr.getAttributeSpellingListIndex()));
5503}
5504
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005505static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5506 const AttributeList &Attr) {
5507 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5508 Attr.getArgAsExpr(0),
5509 Attr.getAttributeSpellingListIndex()));
5510}
5511
5512static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5513 const AttributeList &Attr) {
5514 SmallVector<Expr*, 1> Args;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005515 if (!checkLockFunAttrCommon(S, D, Attr, Args))
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005516 return;
5517
5518 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5519 S.Context,
5520 Args.data(), Args.size(),
5521 Attr.getAttributeSpellingListIndex()));
5522}
5523
5524static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5525 const AttributeList &Attr) {
5526 SmallVector<Expr*, 2> Args;
5527 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5528 return;
5529
5530 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5531 S.Context,
5532 Attr.getArgAsExpr(0),
5533 Args.data(),
5534 Args.size(),
5535 Attr.getAttributeSpellingListIndex()));
5536}
5537
5538static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5539 const AttributeList &Attr) {
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005540 // Check that all arguments are lockable objects.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005541 SmallVector<Expr *, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005542 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005543
Aaron Ballman18d85ae2014-03-20 16:02:49 +00005544 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5545 Attr.getRange(), S.Context, Args.data(), Args.size(),
5546 Attr.getAttributeSpellingListIndex()));
Aaron Ballman9e9d1842014-02-21 21:05:14 +00005547}
5548
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005549static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5550 const AttributeList &Attr) {
5551 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5552 return;
5553
5554 // check that all arguments are lockable objects
5555 SmallVector<Expr*, 1> Args;
Aaron Ballman69e6e7c2014-03-24 19:29:19 +00005556 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
Aaron Ballmanefe348e2014-02-18 17:36:50 +00005557 if (Args.empty())
5558 return;
5559
5560 RequiresCapabilityAttr *RCA = ::new (S.Context)
5561 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5562 Args.size(), Attr.getAttributeSpellingListIndex());
5563
5564 D->addAttr(RCA);
5565}
5566
Aaron Ballman43f40102014-11-14 22:34:56 +00005567static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5568 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5569 if (NSD->isAnonymousNamespace()) {
5570 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5571 // Do not want to attach the attribute to the namespace because that will
5572 // cause confusing diagnostic reports for uses of declarations within the
5573 // namespace.
5574 return;
5575 }
5576 }
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005577
Manman Renc7890fe2016-03-16 18:50:49 +00005578 // Handle the cases where the attribute has a text message.
5579 StringRef Str, Replacement;
5580 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5581 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5582 return;
5583
5584 // Only support a single optional message for Declspec and CXX11.
5585 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5586 checkAttributeAtMostNumArgs(S, Attr, 1);
5587 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5588 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5589 return;
5590
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005591 if (!S.getLangOpts().CPlusPlus14)
5592 if (Attr.isCXX11Attribute() &&
5593 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
Richard Smith4f902c72016-03-08 00:32:55 +00005594 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
Saleem Abdulrasoolf931a382015-02-16 22:27:01 +00005595
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005596 D->addAttr(::new (S.Context)
5597 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5598 Attr.getAttributeSpellingListIndex()));
5599}
5600
5601static bool isGlobalVar(const Decl *D) {
5602 if (const auto *S = dyn_cast<VarDecl>(D))
5603 return S->hasGlobalStorage();
5604 return false;
Aaron Ballman43f40102014-11-14 22:34:56 +00005605}
5606
Peter Collingbourne915df992015-05-15 18:33:32 +00005607static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5608 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5609 return;
5610
Benjamin Kramer1b582012016-02-13 18:11:49 +00005611 std::vector<StringRef> Sanitizers;
Peter Collingbourne915df992015-05-15 18:33:32 +00005612
5613 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5614 StringRef SanitizerName;
5615 SourceLocation LiteralLoc;
5616
5617 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5618 return;
5619
5620 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5621 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005622 else if (isGlobalVar(D) && SanitizerName != "address")
5623 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5624 << Attr.getName() << ExpectedFunctionOrMethod;
Peter Collingbourne915df992015-05-15 18:33:32 +00005625 Sanitizers.push_back(SanitizerName);
5626 }
5627
5628 D->addAttr(::new (S.Context) NoSanitizeAttr(
5629 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5630 Attr.getAttributeSpellingListIndex()));
5631}
5632
5633static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5634 const AttributeList &Attr) {
Aaron Ballman8b5e7ba2015-10-08 19:24:08 +00005635 StringRef AttrName = Attr.getName()->getName();
5636 normalizeName(AttrName);
Douglas Katzman3ed0f642016-10-14 19:55:09 +00005637 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5638 .Case("no_address_safety_analysis", "address")
5639 .Case("no_sanitize_address", "address")
5640 .Case("no_sanitize_thread", "thread")
5641 .Case("no_sanitize_memory", "memory");
5642 if (isGlobalVar(D) && SanitizerName != "address")
5643 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5644 << Attr.getName() << ExpectedFunction;
Peter Collingbourne915df992015-05-15 18:33:32 +00005645 D->addAttr(::new (S.Context)
5646 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5647 Attr.getAttributeSpellingListIndex()));
5648}
5649
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00005650static void handleInternalLinkageAttr(Sema &S, Decl *D,
5651 const AttributeList &Attr) {
5652 if (InternalLinkageAttr *Internal =
5653 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5654 Attr.getAttributeSpellingListIndex()))
5655 D->addAttr(Internal);
5656}
5657
Anastasia Stulovac4bb5df2016-03-31 11:07:22 +00005658static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5659 if (S.LangOpts.OpenCLVersion != 200)
5660 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5661 << Attr.getName() << "2.0" << 0;
5662 else
5663 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5664 << Attr.getName() << "2.0";
5665}
5666
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005667/// Handles semantic checking for features that are common to all attributes,
5668/// such as checking whether a parameter was properly specified, or the correct
5669/// number of arguments were passed, etc.
5670static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5671 const AttributeList &Attr) {
5672 // Several attributes carry different semantics than the parsing requires, so
5673 // those are opted out of the common handling.
5674 //
5675 // We also bail on unknown and ignored attributes because those are handled
5676 // as part of the target-specific handling logic.
5677 if (Attr.hasCustomParsing() ||
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005678 Attr.getKind() == AttributeList::UnknownAttribute)
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005679 return false;
5680
Aaron Ballman3aff6332013-12-02 19:30:36 +00005681 // Check whether the attribute requires specific language extensions to be
5682 // enabled.
5683 if (!Attr.diagnoseLangOpts(S))
5684 return true;
5685
Aaron Ballman8ed8dbd2014-07-31 16:37:04 +00005686 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5687 // If there are no optional arguments, then checking for the argument count
5688 // is trivial.
5689 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5690 return true;
5691 } else {
5692 // There are optional arguments, so checking is slightly more involved.
5693 if (Attr.getMinArgs() &&
5694 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5695 return true;
5696 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5697 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5698 return true;
5699 }
Aaron Ballman74eeeae2013-11-27 13:27:02 +00005700
5701 // Check whether the attribute appertains to the given subject.
5702 if (!Attr.diagnoseAppertainsTo(S, D))
5703 return true;
5704
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005705 return false;
5706}
5707
Xiuli Pan11e13f62016-02-26 03:13:03 +00005708static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5709 const AttributeList &Attr) {
5710 if (D->isInvalidDecl())
5711 return;
5712
5713 // Check if there is only one access qualifier.
5714 if (D->hasAttr<OpenCLAccessAttr>()) {
5715 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5716 << D->getSourceRange();
5717 D->setInvalidDecl(true);
5718 return;
5719 }
5720
5721 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5722 // image object can be read and written.
5723 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5724 // object. Using the read_write (or __read_write) qualifier with the pipe
5725 // qualifier is a compilation error.
5726 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5727 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5728 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5729 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5730 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5731 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5732 D->setInvalidDecl(true);
5733 return;
5734 }
5735 }
5736 }
5737
5738 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5739 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5740}
5741
Ted Kremenek9ecdfaf2009-05-09 02:44:38 +00005742//===----------------------------------------------------------------------===//
Chris Lattner9e2aafe2008-06-29 00:23:49 +00005743// Top Level Sema Entry Points
5744//===----------------------------------------------------------------------===//
5745
Richard Smithf8a75c32013-08-29 00:47:48 +00005746/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5747/// the attribute applies to decls. If the attribute is a type attribute, just
5748/// silently ignore it if a GNU attribute.
5749static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5750 const AttributeList &Attr,
5751 bool IncludeCXX11Attributes) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005752 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
Richard Smithf8a75c32013-08-29 00:47:48 +00005753 return;
Abramo Bagnara50099372010-04-30 13:10:51 +00005754
Richard Smithf8a75c32013-08-29 00:47:48 +00005755 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5756 // instead.
5757 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5758 return;
5759
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005760 // Unknown attributes are automatically warned on. Target-specific attributes
5761 // which do not apply to the current target architecture are treated as
5762 // though they were unknown attributes.
5763 if (Attr.getKind() == AttributeList::UnknownAttribute ||
Bob Wilson7c730832015-07-20 22:57:31 +00005764 !Attr.existsInTarget(S.Context.getTargetInfo())) {
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005765 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5766 ? diag::warn_unhandled_ms_attribute_ignored
5767 : diag::warn_unknown_attribute_ignored)
5768 << Attr.getName();
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005769 return;
5770 }
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005771
Aaron Ballman8ee40b72013-09-09 23:33:17 +00005772 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5773 return;
5774
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005775 switch (Attr.getKind()) {
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005776 default:
Richard Smith4f902c72016-03-08 00:32:55 +00005777 if (!Attr.isStmtAttr()) {
5778 // Type attributes are handled elsewhere; silently move on.
5779 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5780 break;
5781 }
5782 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5783 << Attr.getName() << D->getLocation();
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005784 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005785 case AttributeList::AT_Interrupt:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005786 handleInterruptAttr(S, D, Attr);
5787 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005788 case AttributeList::AT_X86ForceAlignArgPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005789 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5790 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005791 case AttributeList::AT_DLLExport:
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005792 case AttributeList::AT_DLLImport:
Hans Wennborge82f19c2014-06-24 23:57:05 +00005793 handleDLLAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005794 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005795 case AttributeList::AT_Mips16:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005796 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5797 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005798 break;
Aaron Ballmanab7691c2014-01-09 22:48:32 +00005799 case AttributeList::AT_NoMips16:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005800 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5801 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005802 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5803 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5804 break;
5805 case AttributeList::AT_AMDGPUWavesPerEU:
5806 handleAMDGPUWavesPerEUAttr(S, D, Attr);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005807 break;
5808 case AttributeList::AT_AMDGPUNumSGPR:
5809 handleAMDGPUNumSGPRAttr(S, D, Attr);
5810 break;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00005811 case AttributeList::AT_AMDGPUNumVGPR:
5812 handleAMDGPUNumVGPRAttr(S, D, Attr);
5813 break;
Dylan McKaye8232d72017-02-08 05:09:26 +00005814 case AttributeList::AT_AVRSignal:
5815 handleAVRSignalAttr(S, D, Attr);
5816 break;
Aaron Ballman9beb5172013-12-02 15:13:14 +00005817 case AttributeList::AT_IBAction:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005818 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5819 break;
5820 case AttributeList::AT_IBOutlet:
5821 handleIBOutlet(S, D, Attr);
5822 break;
Richard Smith10876ef2013-01-17 01:30:42 +00005823 case AttributeList::AT_IBOutletCollection:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005824 handleIBOutletCollection(S, D, Attr);
5825 break;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00005826 case AttributeList::AT_IFunc:
5827 handleIFuncAttr(S, D, Attr);
5828 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005829 case AttributeList::AT_Alias:
5830 handleAliasAttr(S, D, Attr);
5831 break;
5832 case AttributeList::AT_Aligned:
5833 handleAlignedAttr(S, D, Attr);
5834 break;
Hal Finkel1b0d24e2014-10-02 21:21:25 +00005835 case AttributeList::AT_AlignValue:
5836 handleAlignValueAttr(S, D, Attr);
5837 break;
George Burgess IVe3763372016-12-22 02:50:20 +00005838 case AttributeList::AT_AllocSize:
5839 handleAllocSizeAttr(S, D, Attr);
5840 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005841 case AttributeList::AT_AlwaysInline:
Paul Robinsonf0674352014-03-31 22:29:15 +00005842 handleAlwaysInlineAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005843 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005844 case AttributeList::AT_AnalyzerNoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005845 handleAnalyzerNoReturnAttr(S, D, Attr);
5846 break;
5847 case AttributeList::AT_TLSModel:
5848 handleTLSModelAttr(S, D, Attr);
5849 break;
5850 case AttributeList::AT_Annotate:
5851 handleAnnotateAttr(S, D, Attr);
5852 break;
5853 case AttributeList::AT_Availability:
5854 handleAvailabilityAttr(S, D, Attr);
5855 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005856 case AttributeList::AT_CarriesDependency:
Richard Smithe233fbf2013-01-28 22:42:45 +00005857 handleDependencyAttr(S, scope, D, Attr);
5858 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005859 case AttributeList::AT_Common:
5860 handleCommonAttr(S, D, Attr);
5861 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005862 case AttributeList::AT_CUDAConstant:
Justin Lebare71b2fa2016-09-30 23:57:34 +00005863 handleConstantAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005864 break;
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00005865 case AttributeList::AT_PassObjectSize:
5866 handlePassObjectSizeAttr(S, D, Attr);
5867 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005868 case AttributeList::AT_Constructor:
5869 handleConstructorAttr(S, D, Attr);
5870 break;
Richard Smith10876ef2013-01-17 01:30:42 +00005871 case AttributeList::AT_CXX11NoReturn:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005872 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5873 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005874 case AttributeList::AT_Deprecated:
Aaron Ballman43f40102014-11-14 22:34:56 +00005875 handleDeprecatedAttr(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00005876 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005877 case AttributeList::AT_Destructor:
5878 handleDestructorAttr(S, D, Attr);
5879 break;
5880 case AttributeList::AT_EnableIf:
5881 handleEnableIfAttr(S, D, Attr);
5882 break;
George Burgess IV177399e2017-01-09 04:12:14 +00005883 case AttributeList::AT_DiagnoseIf:
5884 handleDiagnoseIfAttr(S, D, Attr);
5885 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005886 case AttributeList::AT_ExtVectorType:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005887 handleExtVectorTypeAttr(S, scope, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00005888 break;
Alex Lorenzd5d27e12017-03-01 18:06:25 +00005889 case AttributeList::AT_ExternalSourceSymbol:
5890 handleExternalSourceSymbolAttr(S, D, Attr);
5891 break;
Quentin Colombet4e172062012-11-01 23:55:47 +00005892 case AttributeList::AT_MinSize:
Paul Robinsonaae2fba2014-12-10 23:34:36 +00005893 handleMinSizeAttr(S, D, Attr);
Quentin Colombet4e172062012-11-01 23:55:47 +00005894 break;
Paul Robinsonf0674352014-03-31 22:29:15 +00005895 case AttributeList::AT_OptimizeNone:
5896 handleOptimizeNoneAttr(S, D, Attr);
5897 break;
Alexis Hunt724f14e2014-11-28 00:53:20 +00005898 case AttributeList::AT_FlagEnum:
5899 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5900 break;
Akira Hatanaka3c268af2017-03-21 02:23:00 +00005901 case AttributeList::AT_EnumExtensibility:
5902 handleEnumExtensibilityAttr(S, D, Attr);
5903 break;
Peter Collingbourne41af7c22014-05-20 17:12:51 +00005904 case AttributeList::AT_Flatten:
5905 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5906 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005907 case AttributeList::AT_Format:
5908 handleFormatAttr(S, D, Attr);
5909 break;
5910 case AttributeList::AT_FormatArg:
5911 handleFormatArgAttr(S, D, Attr);
5912 break;
5913 case AttributeList::AT_CUDAGlobal:
5914 handleGlobalAttr(S, D, Attr);
5915 break;
Aaron Ballmanf79ee272013-12-02 21:09:08 +00005916 case AttributeList::AT_CUDADevice:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005917 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
5918 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005919 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005920 case AttributeList::AT_CUDAHost:
Justin Lebar3eaaf862016-01-13 01:07:35 +00005921 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
5922 Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005923 break;
5924 case AttributeList::AT_GNUInline:
5925 handleGNUInlineAttr(S, D, Attr);
5926 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005927 case AttributeList::AT_CUDALaunchBounds:
Chandler Carruthedc2c642011-07-02 00:01:44 +00005928 handleLaunchBoundsAttr(S, D, Attr);
Peter Collingbourne827301e2010-12-12 23:03:07 +00005929 break;
David Majnemer631a90b2015-02-04 07:23:21 +00005930 case AttributeList::AT_Restrict:
5931 handleRestrictAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005932 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005933 case AttributeList::AT_MayAlias:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005934 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
5935 break;
5936 case AttributeList::AT_Mode:
5937 handleModeAttr(S, D, Attr);
5938 break;
David Majnemer1bf0f8e2015-07-20 22:51:52 +00005939 case AttributeList::AT_NoAlias:
5940 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
5941 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005942 case AttributeList::AT_NoCommon:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005943 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
5944 break;
Peter Collingbourneb4728c12014-05-19 22:14:34 +00005945 case AttributeList::AT_NoSplitStack:
5946 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
5947 break;
Ted Kremenek9aedc152014-01-17 06:24:56 +00005948 case AttributeList::AT_NonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005949 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
5950 handleNonNullAttrParameter(S, PVD, Attr);
5951 else
5952 handleNonNullAttr(S, D, Attr);
5953 break;
Aaron Ballmanfc1951c2014-01-20 14:19:44 +00005954 case AttributeList::AT_ReturnsNonNull:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005955 handleReturnsNonNullAttr(S, D, Attr);
5956 break;
Hal Finkelee90a222014-09-26 05:04:30 +00005957 case AttributeList::AT_AssumeAligned:
5958 handleAssumeAlignedAttr(S, D, Attr);
5959 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005960 case AttributeList::AT_Overloadable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005961 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
5962 break;
5963 case AttributeList::AT_Ownership:
5964 handleOwnershipAttr(S, D, Attr);
5965 break;
5966 case AttributeList::AT_Cold:
5967 handleColdAttr(S, D, Attr);
5968 break;
5969 case AttributeList::AT_Hot:
5970 handleHotAttr(S, D, Attr);
5971 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00005972 case AttributeList::AT_Naked:
Charles Davis0e379112016-08-08 21:19:08 +00005973 handleNakedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005974 break;
5975 case AttributeList::AT_NoReturn:
5976 handleNoReturnAttr(S, D, Attr);
5977 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00005978 case AttributeList::AT_NoThrow:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005979 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
5980 break;
Aaron Ballman3aff6332013-12-02 19:30:36 +00005981 case AttributeList::AT_CUDAShared:
Justin Lebar10411012016-09-30 23:57:30 +00005982 handleSharedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005983 break;
5984 case AttributeList::AT_VecReturn:
5985 handleVecReturnAttr(S, D, Attr);
5986 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005987 case AttributeList::AT_ObjCOwnership:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005988 handleObjCOwnershipAttr(S, D, Attr);
5989 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005990 case AttributeList::AT_ObjCPreciseLifetime:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005991 handleObjCPreciseLifetimeAttr(S, D, Attr);
5992 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00005993 case AttributeList::AT_ObjCReturnsInnerPointer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005994 handleObjCReturnsInnerPointerAttr(S, D, Attr);
5995 break;
Fariborz Jahanian566fff02012-09-07 23:46:23 +00005996 case AttributeList::AT_ObjCRequiresSuper:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00005997 handleObjCRequiresSuperAttr(S, D, Attr);
5998 break;
Fariborz Jahanian0a0a3972013-11-13 23:59:17 +00005999 case AttributeList::AT_ObjCBridge:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006000 handleObjCBridgeAttr(S, scope, D, Attr);
6001 break;
Fariborz Jahanian87c77912013-11-21 20:50:32 +00006002 case AttributeList::AT_ObjCBridgeMutable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006003 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6004 break;
Fariborz Jahanian1a2519a2013-12-04 20:32:50 +00006005 case AttributeList::AT_ObjCBridgeRelated:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006006 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6007 break;
Argyrios Kyrtzidisd1438b42013-12-03 21:11:25 +00006008 case AttributeList::AT_ObjCDesignatedInitializer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006009 handleObjCDesignatedInitializer(S, D, Attr);
6010 break;
Fariborz Jahanian451b92a2014-07-16 16:16:04 +00006011 case AttributeList::AT_ObjCRuntimeName:
6012 handleObjCRuntimeName(S, D, Attr);
6013 break;
Douglas Gregor24ae22c2016-04-01 23:23:52 +00006014 case AttributeList::AT_ObjCRuntimeVisible:
6015 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6016 break;
Alex Denisovfde64952015-06-26 05:28:36 +00006017 case AttributeList::AT_ObjCBoxable:
6018 handleObjCBoxable(S, D, Attr);
6019 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006020 case AttributeList::AT_CFAuditedTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006021 handleCFAuditedTransferAttr(S, D, Attr);
6022 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006023 case AttributeList::AT_CFUnknownTransfer:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006024 handleCFUnknownTransferAttr(S, D, Attr);
6025 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006026 case AttributeList::AT_CFConsumed:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006027 case AttributeList::AT_NSConsumed:
6028 handleNSConsumedAttr(S, D, Attr);
6029 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006030 case AttributeList::AT_NSConsumesSelf:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006031 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6032 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006033 case AttributeList::AT_NSReturnsAutoreleased:
6034 case AttributeList::AT_NSReturnsNotRetained:
6035 case AttributeList::AT_CFReturnsNotRetained:
6036 case AttributeList::AT_NSReturnsRetained:
6037 case AttributeList::AT_CFReturnsRetained:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006038 handleNSReturnsRetainedAttr(S, D, Attr);
6039 break;
Tanya Lattnerbcffcdf2012-07-09 22:06:01 +00006040 case AttributeList::AT_WorkGroupSizeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006041 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6042 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006043 case AttributeList::AT_ReqdWorkGroupSize:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006044 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6045 break;
Joey Goulyaba589c2013-03-08 09:42:32 +00006046 case AttributeList::AT_VecTypeHint:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006047 handleVecTypeHint(S, D, Attr);
6048 break;
Eric Fiselier341e8252016-09-02 18:53:31 +00006049 case AttributeList::AT_RequireConstantInit:
6050 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6051 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006052 case AttributeList::AT_InitPriority:
6053 handleInitPriorityAttr(S, D, Attr);
6054 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006055 case AttributeList::AT_Packed:
6056 handlePackedAttr(S, D, Attr);
6057 break;
6058 case AttributeList::AT_Section:
6059 handleSectionAttr(S, D, Attr);
6060 break;
Eric Christopher11acf732015-06-12 01:35:52 +00006061 case AttributeList::AT_Target:
6062 handleTargetAttr(S, D, Attr);
6063 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006064 case AttributeList::AT_Unavailable:
Aaron Ballman8b8ebdd2013-07-18 13:13:52 +00006065 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
Benjamin Kramerf435ab42012-05-16 12:19:08 +00006066 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006067 case AttributeList::AT_ArcWeakrefUnavailable:
6068 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6069 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006070 case AttributeList::AT_ObjCRootClass:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006071 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6072 break;
Alex Lorenza8c44ba2016-10-28 10:25:10 +00006073 case AttributeList::AT_ObjCSubclassingRestricted:
6074 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6075 break;
Ted Kremenekf41cf7f12013-12-10 19:43:48 +00006076 case AttributeList::AT_ObjCExplicitProtocolImpl:
Ted Kremenek438f8db2014-02-22 01:06:05 +00006077 handleObjCSuppresProtocolAttr(S, D, Attr);
Ted Kremenek28eace62013-11-23 01:01:34 +00006078 break;
6079 case AttributeList::AT_ObjCRequiresPropertyDefs:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006080 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6081 break;
Aaron Ballman12b9f652014-01-16 13:55:42 +00006082 case AttributeList::AT_Unused:
Aaron Ballman0bcd6c12016-03-09 16:48:08 +00006083 handleUnusedAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006084 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006085 case AttributeList::AT_ReturnsTwice:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006086 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6087 break;
Akira Hatanakac8667622015-11-06 23:56:15 +00006088 case AttributeList::AT_NotTailCalled:
6089 handleNotTailCalledAttr(S, D, Attr);
6090 break;
Akira Hatanaka7828b1e2015-11-13 00:42:21 +00006091 case AttributeList::AT_DisableTailCalls:
6092 handleDisableTailCallsAttr(S, D, Attr);
6093 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006094 case AttributeList::AT_Used:
6095 handleUsedAttr(S, D, Attr);
6096 break;
John McCalld041a9b2013-02-20 01:54:26 +00006097 case AttributeList::AT_Visibility:
6098 handleVisibilityAttr(S, D, Attr, false);
6099 break;
6100 case AttributeList::AT_TypeVisibility:
6101 handleVisibilityAttr(S, D, Attr, true);
6102 break;
Lubos Lunakedc13882013-07-20 15:05:36 +00006103 case AttributeList::AT_WarnUnused:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006104 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6105 break;
6106 case AttributeList::AT_WarnUnusedResult:
6107 handleWarnUnusedResult(S, D, Attr);
Chris Lattner237f2752009-02-14 07:37:35 +00006108 break;
Aaron Ballman604dfec2013-12-02 17:07:07 +00006109 case AttributeList::AT_Weak:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006110 handleSimpleAttribute<WeakAttr>(S, D, Attr);
6111 break;
6112 case AttributeList::AT_WeakRef:
6113 handleWeakRefAttr(S, D, Attr);
6114 break;
6115 case AttributeList::AT_WeakImport:
6116 handleWeakImportAttr(S, D, Attr);
6117 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006118 case AttributeList::AT_TransparentUnion:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006119 handleTransparentUnionAttr(S, D, Attr);
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006120 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006121 case AttributeList::AT_ObjCException:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006122 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6123 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006124 case AttributeList::AT_ObjCMethodFamily:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006125 handleObjCMethodFamilyAttr(S, D, Attr);
John McCall86bc21f2011-03-02 11:33:24 +00006126 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006127 case AttributeList::AT_ObjCNSObject:
6128 handleObjCNSObject(S, D, Attr);
6129 break;
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00006130 case AttributeList::AT_ObjCIndependentClass:
6131 handleObjCIndependentClass(S, D, Attr);
6132 break;
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006133 case AttributeList::AT_Blocks:
6134 handleBlocksAttr(S, D, Attr);
6135 break;
6136 case AttributeList::AT_Sentinel:
6137 handleSentinelAttr(S, D, Attr);
6138 break;
Aaron Ballmanbf7b1ee2013-12-21 16:49:29 +00006139 case AttributeList::AT_Const:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006140 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6141 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006142 case AttributeList::AT_Pure:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006143 handleSimpleAttribute<PureAttr>(S, D, Attr);
6144 break;
6145 case AttributeList::AT_Cleanup:
6146 handleCleanupAttr(S, D, Attr);
6147 break;
6148 case AttributeList::AT_NoDebug:
6149 handleNoDebugAttr(S, D, Attr);
6150 break;
Aaron Ballman7c19ab12014-02-22 16:59:24 +00006151 case AttributeList::AT_NoDuplicate:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006152 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6153 break;
Yaxun Liu7d07ae72016-11-01 18:45:32 +00006154 case AttributeList::AT_Convergent:
6155 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6156 break;
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006157 case AttributeList::AT_NoInline:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006158 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6159 break;
6160 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6161 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6162 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006163 case AttributeList::AT_StdCall:
6164 case AttributeList::AT_CDecl:
6165 case AttributeList::AT_FastCall:
6166 case AttributeList::AT_ThisCall:
6167 case AttributeList::AT_Pascal:
Erich Keane757d3172016-11-02 18:29:35 +00006168 case AttributeList::AT_RegCall:
John McCall477f2bb2016-03-03 06:39:32 +00006169 case AttributeList::AT_SwiftCall:
Reid Klecknerd7857f02014-10-24 17:42:17 +00006170 case AttributeList::AT_VectorCall:
Charles Davisb5a214e2013-08-30 04:39:01 +00006171 case AttributeList::AT_MSABI:
6172 case AttributeList::AT_SysVABI:
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006173 case AttributeList::AT_Pcs:
Guy Benyeif0a014b2012-12-25 08:53:55 +00006174 case AttributeList::AT_IntelOclBicc:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00006175 case AttributeList::AT_PreserveMost:
6176 case AttributeList::AT_PreserveAll:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006177 handleCallConvAttr(S, D, Attr);
John McCallab26cfa2010-02-05 21:31:56 +00006178 break;
Matthias Gehre01a63382017-03-27 19:45:24 +00006179 case AttributeList::AT_Suppress:
6180 handleSuppressAttr(S, D, Attr);
6181 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006182 case AttributeList::AT_OpenCLKernel:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006183 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6184 break;
Xiuli Pan11e13f62016-02-26 03:13:03 +00006185 case AttributeList::AT_OpenCLAccess:
6186 handleOpenCLAccessAttr(S, D, Attr);
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006187 break;
Anastasia Stulovafde76222016-04-01 16:05:09 +00006188 case AttributeList::AT_OpenCLNoSVM:
6189 handleOpenCLNoSVMAttr(S, D, Attr);
6190 break;
John McCall477f2bb2016-03-03 06:39:32 +00006191 case AttributeList::AT_SwiftContext:
6192 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6193 break;
6194 case AttributeList::AT_SwiftErrorResult:
6195 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6196 break;
6197 case AttributeList::AT_SwiftIndirectResult:
6198 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6199 break;
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00006200 case AttributeList::AT_InternalLinkage:
6201 handleInternalLinkageAttr(S, D, Attr);
6202 break;
Peter Collingbourne3afb2662016-04-28 17:09:37 +00006203 case AttributeList::AT_LTOVisibilityPublic:
6204 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6205 break;
John McCall8d32c052012-05-22 21:28:12 +00006206
6207 // Microsoft attributes:
David Majnemercd3ebfe2016-05-23 17:16:12 +00006208 case AttributeList::AT_EmptyBases:
6209 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6210 break;
6211 case AttributeList::AT_LayoutVersion:
6212 handleLayoutVersion(S, D, Attr);
6213 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006214 case AttributeList::AT_MSNoVTable:
6215 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
David Majnemer129f4172015-02-02 10:22:20 +00006216 break;
David Majnemer8ab003a2015-02-02 19:30:52 +00006217 case AttributeList::AT_MSStruct:
6218 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
John McCall8d32c052012-05-22 21:28:12 +00006219 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006220 case AttributeList::AT_Uuid:
Chandler Carruthedc2c642011-07-02 00:01:44 +00006221 handleUuidAttr(S, D, Attr);
Francois Picheta83957a2010-12-19 06:50:37 +00006222 break;
Aaron Ballman8edb5c22013-12-18 23:44:18 +00006223 case AttributeList::AT_MSInheritance:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006224 handleMSInheritanceAttr(S, D, Attr);
6225 break;
Reid Klecknerb144d362013-05-20 14:02:37 +00006226 case AttributeList::AT_SelectAny:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006227 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6228 break;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00006229 case AttributeList::AT_Thread:
6230 handleDeclspecThreadAttr(S, D, Attr);
6231 break;
David Majnemercd3ebfe2016-05-23 17:16:12 +00006232
Dmitry Polukhinbf17ecf2016-03-09 15:30:53 +00006233 case AttributeList::AT_AbiTag:
6234 handleAbiTagAttr(S, D, Attr);
6235 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006236
6237 // Thread safety attributes:
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00006238 case AttributeList::AT_AssertExclusiveLock:
6239 handleAssertExclusiveLockAttr(S, D, Attr);
6240 break;
6241 case AttributeList::AT_AssertSharedLock:
6242 handleAssertSharedLockAttr(S, D, Attr);
6243 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006244 case AttributeList::AT_GuardedVar:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006245 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6246 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006247 case AttributeList::AT_PtGuardedVar:
Michael Han3be3b442012-07-23 18:48:41 +00006248 handlePtGuardedVarAttr(S, D, Attr);
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006249 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006250 case AttributeList::AT_ScopedLockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006251 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6252 break;
Peter Collingbourne915df992015-05-15 18:33:32 +00006253 case AttributeList::AT_NoSanitize:
6254 handleNoSanitizeAttr(S, D, Attr);
6255 break;
6256 case AttributeList::AT_NoSanitizeSpecific:
6257 handleNoSanitizeSpecificAttr(S, D, Attr);
Kostya Serebryany588d6ab2012-01-24 19:25:38 +00006258 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006259 case AttributeList::AT_NoThreadSafetyAnalysis:
Aaron Ballman6f9165a2013-11-27 15:24:06 +00006260 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
Kostya Serebryany4c0fc992013-02-26 06:58:27 +00006261 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006262 case AttributeList::AT_GuardedBy:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006263 handleGuardedByAttr(S, D, Attr);
6264 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006265 case AttributeList::AT_PtGuardedBy:
Michael Han3be3b442012-07-23 18:48:41 +00006266 handlePtGuardedByAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006267 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006268 case AttributeList::AT_ExclusiveTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006269 handleExclusiveTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006270 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006271 case AttributeList::AT_LockReturned:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006272 handleLockReturnedAttr(S, D, Attr);
6273 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006274 case AttributeList::AT_LocksExcluded:
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006275 handleLocksExcludedAttr(S, D, Attr);
6276 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006277 case AttributeList::AT_SharedTrylockFunction:
Michael Han3be3b442012-07-23 18:48:41 +00006278 handleSharedTrylockFunctionAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006279 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006280 case AttributeList::AT_AcquiredBefore:
Michael Han3be3b442012-07-23 18:48:41 +00006281 handleAcquiredBeforeAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006282 break;
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006283 case AttributeList::AT_AcquiredAfter:
Michael Han3be3b442012-07-23 18:48:41 +00006284 handleAcquiredAfterAttr(S, D, Attr);
Caitlin Sadowski63fa6672011-07-28 20:12:35 +00006285 break;
Caitlin Sadowskiaac4d212011-07-28 17:21:07 +00006286
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006287 // Capability analysis attributes.
6288 case AttributeList::AT_Capability:
6289 case AttributeList::AT_Lockable:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006290 handleCapabilityAttr(S, D, Attr);
6291 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006292 case AttributeList::AT_RequiresCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006293 handleRequiresCapabilityAttr(S, D, Attr);
6294 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006295
6296 case AttributeList::AT_AssertCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006297 handleAssertCapabilityAttr(S, D, Attr);
6298 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006299 case AttributeList::AT_AcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006300 handleAcquireCapabilityAttr(S, D, Attr);
6301 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006302 case AttributeList::AT_ReleaseCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006303 handleReleaseCapabilityAttr(S, D, Attr);
6304 break;
Aaron Ballman9e9d1842014-02-21 21:05:14 +00006305 case AttributeList::AT_TryAcquireCapability:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006306 handleTryAcquireCapabilityAttr(S, D, Attr);
6307 break;
Aaron Ballmanefe348e2014-02-18 17:36:50 +00006308
DeLesley Hutchins8d41d992013-10-11 22:30:48 +00006309 // Consumed analysis attributes.
DeLesley Hutchins5a715c42013-08-30 22:56:34 +00006310 case AttributeList::AT_Consumable:
6311 handleConsumableAttr(S, D, Attr);
6312 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006313 case AttributeList::AT_ConsumableAutoCast:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006314 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6315 break;
DeLesley Hutchinsf28bbec2014-01-14 00:36:53 +00006316 case AttributeList::AT_ConsumableSetOnRead:
Aaron Ballman8abdd0e2014-03-06 14:02:27 +00006317 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6318 break;
DeLesley Hutchins210791a2013-10-04 21:28:06 +00006319 case AttributeList::AT_CallableWhen:
6320 handleCallableWhenAttr(S, D, Attr);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006321 break;
DeLesley Hutchins69391772013-10-17 23:23:53 +00006322 case AttributeList::AT_ParamTypestate:
6323 handleParamTypestateAttr(S, D, Attr);
6324 break;
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00006325 case AttributeList::AT_ReturnTypestate:
6326 handleReturnTypestateAttr(S, D, Attr);
6327 break;
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006328 case AttributeList::AT_SetTypestate:
6329 handleSetTypestateAttr(S, D, Attr);
6330 break;
Chris Wailes9385f9f2013-10-29 20:28:41 +00006331 case AttributeList::AT_TestTypestate:
6332 handleTestTypestateAttr(S, D, Attr);
DeLesley Hutchins33a29342013-10-11 23:03:26 +00006333 break;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00006334
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00006335 // Type safety attributes.
6336 case AttributeList::AT_ArgumentWithTypeTag:
6337 handleArgumentWithTypeTagAttr(S, D, Attr);
6338 break;
6339 case AttributeList::AT_TypeTagForDatatype:
6340 handleTypeTagForDatatypeAttr(S, D, Attr);
6341 break;
Pirama Arumuga Nainare5d2d712016-06-10 21:51:18 +00006342 case AttributeList::AT_RenderScriptKernel:
6343 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
Pirama Arumuga Nainar8b788d02016-06-09 23:34:20 +00006344 break;
Aaron Ballman7d2aecb2016-07-13 22:32:15 +00006345 // XRay attributes.
6346 case AttributeList::AT_XRayInstrument:
6347 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6348 break;
Dean Michael Berris418da3f2017-03-06 07:08:21 +00006349 case AttributeList::AT_XRayLogArgs:
6350 handleXRayLogArgsAttr(S, D, Attr);
6351 break;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006352 }
6353}
6354
6355/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6356/// attribute list to the specified decl, ignoring any type attributes.
Eric Christopherbc638a82010-12-01 22:13:54 +00006357void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
Peter Collingbourneb331b262011-01-21 02:08:45 +00006358 const AttributeList *AttrList,
Richard Smith10876ef2013-01-17 01:30:42 +00006359 bool IncludeCXX11Attributes) {
6360 for (const AttributeList* l = AttrList; l; l = l->getNext())
Richard Smithf8a75c32013-08-29 00:47:48 +00006361 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
Rafael Espindolac18086a2010-02-23 22:00:30 +00006362
Joey Gouly2cd9db12013-12-13 16:15:28 +00006363 // FIXME: We should be able to handle these cases in TableGen.
Rafael Espindolac18086a2010-02-23 22:00:30 +00006364 // GCC accepts
6365 // static int a9 __attribute__((weakref));
6366 // but that looks really pointless. We reject it.
Richard Smithf8a75c32013-08-29 00:47:48 +00006367 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
Aaron Ballman9f6fec42014-01-02 23:02:01 +00006368 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6369 << cast<NamedDecl>(D);
Rafael Espindolab3069002013-01-16 23:49:06 +00006370 D->dropAttr<WeakRefAttr>();
Rafael Espindolac18086a2010-02-23 22:00:30 +00006371 return;
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006372 }
Joey Gouly2cd9db12013-12-13 16:15:28 +00006373
Aaron Ballmanbe243a72014-12-04 22:45:31 +00006374 // FIXME: We should be able to handle this in TableGen as well. It would be
6375 // good to have a way to specify "these attributes must appear as a group",
6376 // for these. Additionally, it would be good to have a way to specify "these
6377 // attribute must never appear as a group" for attributes like cold and hot.
Joey Gouly2cd9db12013-12-13 16:15:28 +00006378 if (!D->hasAttr<OpenCLKernelAttr>()) {
6379 // These attributes cannot be applied to a non-kernel function.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006380 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006381 // FIXME: This emits a different error message than
6382 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
Aaron Ballman3e424b52013-12-26 18:30:57 +00006383 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006384 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006385 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006386 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006387 D->setInvalidDecl();
Matt Arsenault43cfcbc2014-12-05 18:03:55 +00006388 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
Aaron Ballman3e424b52013-12-26 18:30:57 +00006389 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
Joey Gouly2cd9db12013-12-13 16:15:28 +00006390 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006391 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6392 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6393 << A << ExpectedKernelFunction;
6394 D->setInvalidDecl();
6395 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
Matt Arsenaultb9e9dc52014-12-05 18:03:58 +00006396 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6397 << A << ExpectedKernelFunction;
6398 D->setInvalidDecl();
6399 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6400 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6401 << A << ExpectedKernelFunction;
6402 D->setInvalidDecl();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00006403 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6404 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6405 << A << ExpectedKernelFunction;
6406 D->setInvalidDecl();
Joey Gouly2cd9db12013-12-13 16:15:28 +00006407 }
6408 }
Chris Lattnerb632a6e2008-06-29 00:43:07 +00006409}
6410
Erich Keane2fe684b2017-02-28 20:44:39 +00006411// Helper for delayed proccessing TransparentUnion attribute.
6412void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6413 for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6414 if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6415 handleTransparentUnionAttr(*this, D, *Attr);
6416 break;
6417 }
6418}
6419
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006420// Annotation attributes are the only attributes allowed after an access
6421// specifier.
6422bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6423 const AttributeList *AttrList) {
6424 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
Alexis Hunt3bc72c12012-06-19 23:57:03 +00006425 if (l->getKind() == AttributeList::AT_Annotate) {
David Majnemer706f3152014-12-14 01:05:01 +00006426 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00006427 } else {
6428 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6429 return true;
6430 }
6431 }
6432
6433 return false;
6434}
6435
John McCall42856de2011-10-01 05:17:03 +00006436/// checkUnusedDeclAttributes - Check a list of attributes to see if it
6437/// contains any decl attributes that we should warn about.
6438static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6439 for ( ; A; A = A->getNext()) {
6440 // Only warn if the attribute is an unignored, non-type attribute.
Richard Smith810ad3e2013-01-29 10:02:16 +00006441 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
John McCall42856de2011-10-01 05:17:03 +00006442 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6443
6444 if (A->getKind() == AttributeList::UnknownAttribute) {
6445 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6446 << A->getName() << A->getRange();
6447 } else {
6448 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6449 << A->getName() << A->getRange();
6450 }
6451 }
6452}
6453
6454/// checkUnusedDeclAttributes - Given a declarator which is not being
6455/// used to build a declaration, complain about any decl attributes
6456/// which might be lying around on it.
6457void Sema::checkUnusedDeclAttributes(Declarator &D) {
6458 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6459 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6460 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6461 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6462}
6463
Ryan Flynn7d470f32009-07-30 03:15:39 +00006464/// DeclClonePragmaWeak - clone existing decl (maybe definition),
James Dennett634962f2012-06-14 21:40:34 +00006465/// \#pragma weak needs a non-definition decl and source may not have one.
Eli Friedmance3e2c82011-09-07 04:05:06 +00006466NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6467 SourceLocation Loc) {
Ryan Flynnd963a492009-07-31 02:52:19 +00006468 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
Craig Topperc3ec1492014-05-26 06:22:03 +00006469 NamedDecl *NewD = nullptr;
Ryan Flynn7d470f32009-07-30 03:15:39 +00006470 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Alexander Kornienko061900f2015-12-03 11:37:28 +00006471 FunctionDecl *NewFD;
6472 // FIXME: Missing call to CheckFunctionDeclaration().
Eli Friedmance3e2c82011-09-07 04:05:06 +00006473 // FIXME: Mangling?
6474 // FIXME: Is the qualifier info correct?
6475 // FIXME: Is the DeclContext correct?
Alexander Kornienko061900f2015-12-03 11:37:28 +00006476 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6477 Loc, Loc, DeclarationName(II),
6478 FD->getType(), FD->getTypeSourceInfo(),
6479 SC_None, false/*isInlineSpecified*/,
6480 FD->hasPrototype(),
6481 false/*isConstexprSpecified*/);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006482 NewD = NewFD;
6483
6484 if (FD->getQualifier())
Douglas Gregor14454802011-02-25 02:25:35 +00006485 NewFD->setQualifierInfo(FD->getQualifierLoc());
Eli Friedmance3e2c82011-09-07 04:05:06 +00006486
6487 // Fake up parameter variables; they are declared as if this were
6488 // a typedef.
6489 QualType FDTy = FD->getType();
6490 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6491 SmallVector<ParmVarDecl*, 16> Params;
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006492 for (const auto &AI : FT->param_types()) {
6493 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
Eli Friedmance3e2c82011-09-07 04:05:06 +00006494 Param->setScopeInfo(0, Params.size());
6495 Params.push_back(Param);
6496 }
David Blaikie9c70e042011-09-21 18:16:56 +00006497 NewFD->setParams(Params);
John McCall3e11ebe2010-03-15 10:12:16 +00006498 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006499 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6500 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00006501 VD->getInnerLocStart(), VD->getLocation(), II,
John McCallbcd03502009-12-07 02:54:59 +00006502 VD->getType(), VD->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00006503 VD->getStorageClass());
John McCall3e11ebe2010-03-15 10:12:16 +00006504 if (VD->getQualifier()) {
6505 VarDecl *NewVD = cast<VarDecl>(NewD);
Douglas Gregor14454802011-02-25 02:25:35 +00006506 NewVD->setQualifierInfo(VD->getQualifierLoc());
John McCall3e11ebe2010-03-15 10:12:16 +00006507 }
Ryan Flynn7d470f32009-07-30 03:15:39 +00006508 }
6509 return NewD;
6510}
6511
James Dennett634962f2012-06-14 21:40:34 +00006512/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
Ryan Flynn7d470f32009-07-30 03:15:39 +00006513/// applied to it, possibly with an alias.
Ryan Flynnd963a492009-07-31 02:52:19 +00006514void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
Chris Lattnere6eab982009-09-08 18:10:11 +00006515 if (W.getUsed()) return; // only do this once
6516 W.setUsed(true);
6517 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6518 IdentifierInfo *NDId = ND->getIdentifier();
Eli Friedmance3e2c82011-09-07 04:05:06 +00006519 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
Aaron Ballman36a53502014-01-16 13:03:14 +00006520 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6521 W.getLocation()));
6522 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Chris Lattnere6eab982009-09-08 18:10:11 +00006523 WeakTopLevelDecl.push_back(NewD);
6524 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6525 // to insert Decl at TU scope, sorry.
6526 DeclContext *SavedContext = CurContext;
6527 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis0098a4b2014-03-09 05:15:28 +00006528 NewD->setDeclContext(CurContext);
6529 NewD->setLexicalDeclContext(CurContext);
Chris Lattnere6eab982009-09-08 18:10:11 +00006530 PushOnScopeChains(NewD, S);
6531 CurContext = SavedContext;
6532 } else { // just add weak to existing
Aaron Ballman36a53502014-01-16 13:03:14 +00006533 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
Ryan Flynn7d470f32009-07-30 03:15:39 +00006534 }
6535}
6536
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006537void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6538 // It's valid to "forward-declare" #pragma weak, in which case we
6539 // have to do this.
6540 LoadExternalWeakUndeclaredIdentifiers();
6541 if (!WeakUndeclaredIdentifiers.empty()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006542 NamedDecl *ND = nullptr;
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006543 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6544 if (VD->isExternC())
6545 ND = VD;
6546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6547 if (FD->isExternC())
6548 ND = FD;
6549 if (ND) {
6550 if (IdentifierInfo *Id = ND->getIdentifier()) {
Chandler Carruthf85d9822015-03-26 08:32:49 +00006551 auto I = WeakUndeclaredIdentifiers.find(Id);
Rafael Espindolade6a39f2013-03-02 21:41:48 +00006552 if (I != WeakUndeclaredIdentifiers.end()) {
6553 WeakInfo W = I->second;
6554 DeclApplyPragmaWeak(S, ND, W);
6555 WeakUndeclaredIdentifiers[Id] = W;
6556 }
6557 }
6558 }
6559 }
6560}
6561
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006562/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6563/// it, apply them to D. This is a bit tricky because PD can have attributes
6564/// specified in many different places, and we need to find and apply them all.
Richard Smithf8a75c32013-08-29 00:47:48 +00006565void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006566 // Apply decl attributes from the DeclSpec if present.
John McCall53fa7142010-12-24 02:08:15 +00006567 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
Richard Smithf8a75c32013-08-29 00:47:48 +00006568 ProcessDeclAttributeList(S, D, Attrs);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006569
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006570 // Walk the declarator structure, applying decl attributes that were in a type
6571 // position to the decl itself. This handles cases like:
6572 // int *__attr__(x)** D;
6573 // when X is a decl attribute.
6574 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6575 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
Richard Smithf8a75c32013-08-29 00:47:48 +00006576 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
Mike Stumpd3bb5572009-07-24 19:02:52 +00006577
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006578 // Finally, apply any attributes on the decl itself.
6579 if (const AttributeList *Attrs = PD.getAttributes())
Richard Smithf8a75c32013-08-29 00:47:48 +00006580 ProcessDeclAttributeList(S, D, Attrs);
Chris Lattner9e2aafe2008-06-29 00:23:49 +00006581}
John McCall28a6aea2009-11-04 02:18:39 +00006582
John McCall31168b02011-06-15 23:02:42 +00006583/// Is the given declaration allowed to use a forbidden type?
John McCallb61e14e2015-10-27 04:54:50 +00006584/// If so, it'll still be annotated with an attribute that makes it
6585/// illegal to actually use.
6586static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6587 const DelayedDiagnostic &diag,
John McCallc6af8c62015-10-28 05:03:19 +00006588 UnavailableAttr::ImplicitReason &reason) {
John McCall31168b02011-06-15 23:02:42 +00006589 // Private ivars are always okay. Unfortunately, people don't
6590 // always properly make their ivars private, even in system headers.
6591 // Plus we need to make fields okay, too.
Fariborz Jahanian6d5d6a22011-09-26 21:23:35 +00006592 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6593 !isa<FunctionDecl>(decl))
John McCall31168b02011-06-15 23:02:42 +00006594 return false;
6595
John McCallc6af8c62015-10-28 05:03:19 +00006596 // Silently accept unsupported uses of __weak in both user and system
6597 // declarations when it's been disabled, for ease of integration with
6598 // -fno-objc-arc files. We do have to take some care against attempts
6599 // to define such things; for now, we've only done that for ivars
6600 // and properties.
6601 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6602 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6603 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6604 reason = UnavailableAttr::IR_ForbiddenWeak;
6605 return true;
6606 }
John McCallb61e14e2015-10-27 04:54:50 +00006607 }
6608
John McCallc6af8c62015-10-28 05:03:19 +00006609 // Allow all sorts of things in system headers.
6610 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6611 // Currently, all the failures dealt with this way are due to ARC
6612 // restrictions.
6613 reason = UnavailableAttr::IR_ARCForbiddenType;
6614 return true;
John McCallb61e14e2015-10-27 04:54:50 +00006615 }
6616
6617 return false;
John McCall31168b02011-06-15 23:02:42 +00006618}
6619
6620/// Handle a delayed forbidden-type diagnostic.
6621static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6622 Decl *decl) {
John McCallc6af8c62015-10-28 05:03:19 +00006623 auto reason = UnavailableAttr::IR_None;
6624 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6625 assert(reason && "didn't set reason?");
6626 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6627 diag.Loc));
John McCall31168b02011-06-15 23:02:42 +00006628 return;
6629 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00006630 if (S.getLangOpts().ObjCAutoRefCount)
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006631 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
Benjamin Kramer474261a2012-06-02 10:20:41 +00006632 // FIXME: we may want to suppress diagnostics for all
Fariborz Jahanianed1933b2011-10-03 22:11:57 +00006633 // kind of forbidden type messages on unavailable functions.
6634 if (FD->hasAttr<UnavailableAttr>() &&
6635 diag.getForbiddenTypeDiagnostic() ==
6636 diag::err_arc_array_param_no_ownership) {
6637 diag.Triggered = true;
6638 return;
6639 }
6640 }
John McCall31168b02011-06-15 23:02:42 +00006641
6642 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6643 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6644 diag.Triggered = true;
6645}
6646
Manman Ren45b1ab12016-05-06 19:57:16 +00006647static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6648 const Decl *D) {
6649 // Check each AvailabilityAttr to find the one for this platform.
6650 for (const auto *A : D->attrs()) {
6651 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6652 // FIXME: this is copied from CheckAvailability. We should try to
6653 // de-duplicate.
6654
6655 // Check if this is an App Extension "platform", and if so chop off
6656 // the suffix for matching with the actual platform.
6657 StringRef ActualPlatform = Avail->getPlatform()->getName();
6658 StringRef RealizedPlatform = ActualPlatform;
6659 if (Context.getLangOpts().AppExt) {
6660 size_t suffix = RealizedPlatform.rfind("_app_extension");
6661 if (suffix != StringRef::npos)
6662 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6663 }
6664
6665 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6666
6667 // Match the platform name.
6668 if (RealizedPlatform == TargetPlatform)
6669 return Avail;
6670 }
6671 }
6672 return nullptr;
6673}
6674
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00006675/// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6676/// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6677/// in a deprecated context, but not the other way around.
6678static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6679 VersionTuple DeclVersion,
6680 Decl *Ctx) {
6681 assert(K != AR_Available && "Expected an unavailable declaration here!");
6682
6683 // Checks if we should emit the availability diagnostic in the context of C.
6684 auto CheckContext = [&](const Decl *C) {
6685 if (K == AR_NotYetIntroduced) {
6686 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6687 if (AA->getIntroduced() >= DeclVersion)
6688 return true;
6689 } else if (K == AR_Deprecated)
6690 if (C->isDeprecated())
6691 return true;
6692
6693 if (C->isUnavailable())
6694 return true;
6695 return false;
6696 };
6697
6698 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6699 // on nested declarations in an @interface having the availability of the
6700 // interface when they really shouldn't: they are members of the enclosing
6701 // context, and can referenced from there.
6702 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6703 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6704 if (CheckContext(OrigCtx))
6705 return false;
6706
6707 // An implementation implicitly has the availability of the interface.
6708 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6709 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6710 if (CheckContext(Interface))
6711 return false;
6712 }
6713 // A category implicitly has the availability of the interface.
6714 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6715 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6716 if (CheckContext(Interface))
6717 return false;
6718 }
6719
6720 do {
6721 if (CheckContext(Ctx))
6722 return false;
6723
6724 // An implementation implicitly has the availability of the interface.
6725 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
6726 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6727 if (CheckContext(Interface))
6728 return false;
6729 }
6730 // A category implicitly has the availability of the interface.
6731 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
6732 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6733 if (CheckContext(Interface))
6734 return false;
6735 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
6736
6737 return true;
6738}
6739
Erik Pilkington796a3e22016-08-05 22:59:03 +00006740static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
Aaron Ballmanfb237522014-10-15 15:37:51 +00006741 Decl *Ctx, const NamedDecl *D,
6742 StringRef Message, SourceLocation Loc,
6743 const ObjCInterfaceDecl *UnknownObjCClass,
6744 const ObjCPropertyDecl *ObjCProperty,
6745 bool ObjCPropertyAccess) {
6746 // Diagnostics for deprecated or unavailable.
6747 unsigned diag, diag_message, diag_fwdclass_message;
John McCallb61e14e2015-10-27 04:54:50 +00006748 unsigned diag_available_here = diag::note_availability_specified_here;
Erich Keanea32910d2017-03-23 18:51:54 +00006749 SourceLocation NoteLocation = D->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00006750
6751 // Matches 'diag::note_property_attribute' options.
6752 unsigned property_note_select;
6753
6754 // Matches diag::note_availability_specified_here.
6755 unsigned available_here_select_kind;
6756
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00006757 VersionTuple DeclVersion;
6758 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D))
6759 DeclVersion = AA->getIntroduced();
6760
6761 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
6762 return;
6763
Aaron Ballmanfb237522014-10-15 15:37:51 +00006764 switch (K) {
Erik Pilkington796a3e22016-08-05 22:59:03 +00006765 case AR_Deprecated:
Aaron Ballmanfb237522014-10-15 15:37:51 +00006766 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6767 : diag::warn_property_method_deprecated;
6768 diag_message = diag::warn_deprecated_message;
6769 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6770 property_note_select = /* deprecated */ 0;
6771 available_here_select_kind = /* deprecated */ 2;
Erich Keanea32910d2017-03-23 18:51:54 +00006772 if (const auto *attr = D->getAttr<DeprecatedAttr>())
6773 NoteLocation = attr->getLocation();
Aaron Ballmanfb237522014-10-15 15:37:51 +00006774 break;
6775
Erik Pilkington796a3e22016-08-05 22:59:03 +00006776 case AR_Unavailable:
Aaron Ballmanfb237522014-10-15 15:37:51 +00006777 diag = !ObjCPropertyAccess ? diag::err_unavailable
6778 : diag::err_property_method_unavailable;
6779 diag_message = diag::err_unavailable_message;
6780 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6781 property_note_select = /* unavailable */ 1;
6782 available_here_select_kind = /* unavailable */ 0;
John McCallb61e14e2015-10-27 04:54:50 +00006783
John McCallc6af8c62015-10-28 05:03:19 +00006784 if (auto attr = D->getAttr<UnavailableAttr>()) {
6785 if (attr->isImplicit() && attr->getImplicitReason()) {
6786 // Most of these failures are due to extra restrictions in ARC;
6787 // reflect that in the primary diagnostic when applicable.
6788 auto flagARCError = [&] {
6789 if (S.getLangOpts().ObjCAutoRefCount &&
6790 S.getSourceManager().isInSystemHeader(D->getLocation()))
6791 diag = diag::err_unavailable_in_arc;
6792 };
6793
6794 switch (attr->getImplicitReason()) {
6795 case UnavailableAttr::IR_None: break;
6796
6797 case UnavailableAttr::IR_ARCForbiddenType:
6798 flagARCError();
6799 diag_available_here = diag::note_arc_forbidden_type;
6800 break;
6801
6802 case UnavailableAttr::IR_ForbiddenWeak:
6803 if (S.getLangOpts().ObjCWeakRuntime)
6804 diag_available_here = diag::note_arc_weak_disabled;
6805 else
6806 diag_available_here = diag::note_arc_weak_no_runtime;
6807 break;
6808
6809 case UnavailableAttr::IR_ARCForbiddenConversion:
6810 flagARCError();
6811 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6812 break;
6813
6814 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6815 flagARCError();
6816 diag_available_here = diag::note_arc_init_returns_unrelated;
6817 break;
6818
6819 case UnavailableAttr::IR_ARCFieldWithOwnership:
6820 flagARCError();
6821 diag_available_here = diag::note_arc_field_with_ownership;
6822 break;
6823 }
6824 }
John McCallb61e14e2015-10-27 04:54:50 +00006825 }
Aaron Ballmanfb237522014-10-15 15:37:51 +00006826 break;
6827
Erik Pilkington796a3e22016-08-05 22:59:03 +00006828 case AR_NotYetIntroduced:
Nico Weber0055a192015-03-19 19:18:22 +00006829 diag = diag::warn_partial_availability;
6830 diag_message = diag::warn_partial_message;
6831 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6832 property_note_select = /* partial */ 2;
6833 available_here_select_kind = /* partial */ 3;
6834 break;
Erik Pilkington796a3e22016-08-05 22:59:03 +00006835
6836 case AR_Available:
6837 llvm_unreachable("Warning for availability of available declaration?");
Aaron Ballmanfb237522014-10-15 15:37:51 +00006838 }
6839
Manman Renc7890fe2016-03-16 18:50:49 +00006840 CharSourceRange UseRange;
6841 StringRef Replacement;
Erik Pilkington796a3e22016-08-05 22:59:03 +00006842 if (K == AR_Deprecated) {
Manman Renc7890fe2016-03-16 18:50:49 +00006843 if (auto attr = D->getAttr<DeprecatedAttr>())
6844 Replacement = attr->getReplacement();
Manman Ren45b1ab12016-05-06 19:57:16 +00006845 if (auto attr = getAttrForPlatform(S.Context, D))
Manman Ren75bc6762016-03-21 17:30:55 +00006846 Replacement = attr->getReplacement();
Manman Renc7890fe2016-03-16 18:50:49 +00006847
6848 if (!Replacement.empty())
6849 UseRange =
6850 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6851 }
6852
Aaron Ballmanfb237522014-10-15 15:37:51 +00006853 if (!Message.empty()) {
Manman Renc7890fe2016-03-16 18:50:49 +00006854 S.Diag(Loc, diag_message) << D << Message
6855 << (UseRange.isValid() ?
6856 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006857 if (ObjCProperty)
6858 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6859 << ObjCProperty->getDeclName() << property_note_select;
6860 } else if (!UnknownObjCClass) {
Manman Renc7890fe2016-03-16 18:50:49 +00006861 S.Diag(Loc, diag) << D
6862 << (UseRange.isValid() ?
6863 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006864 if (ObjCProperty)
6865 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6866 << ObjCProperty->getDeclName() << property_note_select;
6867 } else {
Manman Renc7890fe2016-03-16 18:50:49 +00006868 S.Diag(Loc, diag_fwdclass_message) << D
6869 << (UseRange.isValid() ?
6870 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
Aaron Ballmanfb237522014-10-15 15:37:51 +00006871 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6872 }
6873
Manman Ren45b1ab12016-05-06 19:57:16 +00006874 // The declaration can have multiple availability attributes, we are looking
6875 // at one of them.
6876 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6877 if (A && A->isInherited()) {
6878 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6879 Redecl = Redecl->getPreviousDecl()) {
6880 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6881 Redecl);
6882 if (AForRedecl && !AForRedecl->isInherited()) {
6883 // If D is a declaration with inherited attributes, the note should
6884 // point to the declaration with actual attributes.
6885 S.Diag(Redecl->getLocation(), diag_available_here) << D
6886 << available_here_select_kind;
6887 break;
6888 }
6889 }
6890 }
6891 else
Erich Keanea32910d2017-03-23 18:51:54 +00006892 S.Diag(NoteLocation, diag_available_here)
Manman Ren45b1ab12016-05-06 19:57:16 +00006893 << D << available_here_select_kind;
6894
Erik Pilkington796a3e22016-08-05 22:59:03 +00006895 if (K == AR_NotYetIntroduced)
Nico Weber0055a192015-03-19 19:18:22 +00006896 S.Diag(Loc, diag::note_partial_availability_silence) << D;
Aaron Ballmanfb237522014-10-15 15:37:51 +00006897}
6898
6899static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6900 Decl *Ctx) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00006901 assert(DD.Kind == DelayedDiagnostic::Availability &&
6902 "Expected an availability diagnostic here");
6903
Aaron Ballmanfb237522014-10-15 15:37:51 +00006904 DD.Triggered = true;
Nico Weber0055a192015-03-19 19:18:22 +00006905 DoEmitAvailabilityWarning(
Erik Pilkingtona8003972016-10-28 21:39:27 +00006906 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(),
6907 DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(),
6908 DD.getObjCProperty(), false);
Aaron Ballmanfb237522014-10-15 15:37:51 +00006909}
6910
John McCall2ec85372012-05-07 06:16:41 +00006911void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
6912 assert(DelayedDiagnostics.getCurrentPool());
John McCall6347b682012-05-07 06:16:58 +00006913 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
John McCall2ec85372012-05-07 06:16:41 +00006914 DelayedDiagnostics.popWithoutEmitting(state);
John McCallc1465822011-02-14 07:13:47 +00006915
John McCall2ec85372012-05-07 06:16:41 +00006916 // When delaying diagnostics to run in the context of a parsed
6917 // declaration, we only want to actually emit anything if parsing
6918 // succeeds.
6919 if (!decl) return;
John McCallc1465822011-02-14 07:13:47 +00006920
John McCall2ec85372012-05-07 06:16:41 +00006921 // We emit all the active diagnostics in this pool or any of its
6922 // parents. In general, we'll get one pool for the decl spec
6923 // and a child pool for each declarator; in a decl group like:
6924 // deprecated_typedef foo, *bar, baz();
6925 // only the declarator pops will be passed decls. This is correct;
6926 // we really do need to consider delayed diagnostics from the decl spec
6927 // for each of the different declarations.
John McCall6347b682012-05-07 06:16:58 +00006928 const DelayedDiagnosticPool *pool = &poppedPool;
John McCall2ec85372012-05-07 06:16:41 +00006929 do {
John McCall6347b682012-05-07 06:16:58 +00006930 for (DelayedDiagnosticPool::pool_iterator
John McCall2ec85372012-05-07 06:16:41 +00006931 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
6932 // This const_cast is a bit lame. Really, Triggered should be mutable.
6933 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
John McCallc1465822011-02-14 07:13:47 +00006934 if (diag.Triggered)
John McCall86121512010-01-27 03:50:35 +00006935 continue;
6936
John McCallc1465822011-02-14 07:13:47 +00006937 switch (diag.Kind) {
Erik Pilkingtona8003972016-10-28 21:39:27 +00006938 case DelayedDiagnostic::Availability:
Ted Kremenekb79ee572013-12-18 23:30:06 +00006939 // Don't bother giving deprecation/unavailable diagnostics if
6940 // the decl is invalid.
John McCall18a962b2012-01-26 20:04:03 +00006941 if (!decl->isInvalidDecl())
Aaron Ballmanfb237522014-10-15 15:37:51 +00006942 handleDelayedAvailabilityCheck(*this, diag, decl);
John McCall86121512010-01-27 03:50:35 +00006943 break;
6944
6945 case DelayedDiagnostic::Access:
John McCall2ec85372012-05-07 06:16:41 +00006946 HandleDelayedAccessCheck(diag, decl);
John McCall86121512010-01-27 03:50:35 +00006947 break;
John McCall31168b02011-06-15 23:02:42 +00006948
6949 case DelayedDiagnostic::ForbiddenType:
John McCall2ec85372012-05-07 06:16:41 +00006950 handleDelayedForbiddenType(*this, diag, decl);
John McCall31168b02011-06-15 23:02:42 +00006951 break;
John McCall86121512010-01-27 03:50:35 +00006952 }
6953 }
John McCall2ec85372012-05-07 06:16:41 +00006954 } while ((pool = pool->getParent()));
John McCall28a6aea2009-11-04 02:18:39 +00006955}
6956
John McCall6347b682012-05-07 06:16:58 +00006957/// Given a set of delayed diagnostics, re-emit them as if they had
6958/// been delayed in the current context instead of in the given pool.
6959/// Essentially, this just moves them to the current pool.
6960void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
6961 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
6962 assert(curPool && "re-emitting in undelayed context not supported");
6963 curPool->steal(pool);
6964}
6965
Erik Pilkington796a3e22016-08-05 22:59:03 +00006966void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
Ted Kremenekb79ee572013-12-18 23:30:06 +00006967 NamedDecl *D, StringRef Message,
6968 SourceLocation Loc,
6969 const ObjCInterfaceDecl *UnknownObjCClass,
Fariborz Jahanian89ea9612014-06-16 17:25:41 +00006970 const ObjCPropertyDecl *ObjCProperty,
6971 bool ObjCPropertyAccess) {
John McCall28a6aea2009-11-04 02:18:39 +00006972 // Delay if we're currently parsing a declaration.
Erik Pilkingtona8003972016-10-28 21:39:27 +00006973 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
Nico Weber462fd1e2015-01-07 23:50:05 +00006974 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
Erik Pilkington796a3e22016-08-05 22:59:03 +00006975 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
Nico Weber462fd1e2015-01-07 23:50:05 +00006976 ObjCPropertyAccess));
John McCall28a6aea2009-11-04 02:18:39 +00006977 return;
6978 }
6979
Ted Kremenekb79ee572013-12-18 23:30:06 +00006980 Decl *Ctx = cast<Decl>(getCurLexicalContext());
Erik Pilkington796a3e22016-08-05 22:59:03 +00006981 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
Nico Weber0055a192015-03-19 19:18:22 +00006982 ObjCProperty, ObjCPropertyAccess);
John McCall28a6aea2009-11-04 02:18:39 +00006983}
Erik Pilkington48c7cc92016-07-29 17:37:38 +00006984
Erik Pilkington5cd57172016-08-16 17:44:11 +00006985namespace {
6986
6987/// \brief This class implements -Wunguarded-availability.
6988///
6989/// This is done with a traversal of the AST of a function that makes reference
6990/// to a partially available declaration. Whenever we encounter an \c if of the
6991/// form: \c if(@available(...)), we use the version from the condition to visit
6992/// the then statement.
6993class DiagnoseUnguardedAvailability
6994 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
6995 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
6996
6997 Sema &SemaRef;
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00006998 Decl *Ctx;
Erik Pilkington5cd57172016-08-16 17:44:11 +00006999
7000 /// Stack of potentially nested 'if (@available(...))'s.
7001 SmallVector<VersionTuple, 8> AvailabilityStack;
7002
7003 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7004
7005public:
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007006 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7007 : SemaRef(SemaRef), Ctx(Ctx) {
7008 AvailabilityStack.push_back(
7009 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
Erik Pilkington5cd57172016-08-16 17:44:11 +00007010 }
7011
7012 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7013
7014 bool TraverseIfStmt(IfStmt *If);
7015
7016 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7017 if (ObjCMethodDecl *D = Msg->getMethodDecl())
7018 DiagnoseDeclAvailability(
7019 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7020 return true;
7021 }
7022
7023 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7024 DiagnoseDeclAvailability(DRE->getDecl(),
7025 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7026 return true;
7027 }
7028
7029 bool VisitMemberExpr(MemberExpr *ME) {
7030 DiagnoseDeclAvailability(ME->getMemberDecl(),
7031 SourceRange(ME->getLocStart(), ME->getLocEnd()));
7032 return true;
7033 }
7034
7035 bool VisitTypeLoc(TypeLoc Ty);
7036};
7037
7038void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7039 NamedDecl *D, SourceRange Range) {
7040
7041 VersionTuple ContextVersion = AvailabilityStack.back();
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007042 if (AvailabilityResult Result =
7043 SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) {
Erik Pilkington5cd57172016-08-16 17:44:11 +00007044 // All other diagnostic kinds have already been handled in
7045 // DiagnoseAvailabilityOfDecl.
7046 if (Result != AR_NotYetIntroduced)
7047 return;
7048
7049 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
7050 VersionTuple Introduced = AA->getIntroduced();
7051
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007052 if (ContextVersion >= Introduced)
7053 return;
7054
7055 // If the context of this function is less available than D, we should not
7056 // emit a diagnostic.
7057 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7058 return;
7059
Erik Pilkington5cd57172016-08-16 17:44:11 +00007060 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
7061 << Range << D
7062 << AvailabilityAttr::getPrettyPlatformName(
7063 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7064 << Introduced.getAsString();
7065
7066 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
7067 << D << /* partial */ 3;
7068
7069 // FIXME: Replace this with a fixit diagnostic.
7070 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7071 << Range << D;
7072 }
7073}
7074
7075bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7076 const Type *TyPtr = Ty.getTypePtr();
7077 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7078
7079 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7080 TagDecl *TD = TT->getDecl();
7081 DiagnoseDeclAvailability(TD, Range);
7082
7083 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7084 TypedefNameDecl *D = TD->getDecl();
7085 DiagnoseDeclAvailability(D, Range);
7086
7087 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7088 if (NamedDecl *D = ObjCO->getInterface())
7089 DiagnoseDeclAvailability(D, Range);
7090 }
7091
7092 return true;
7093}
7094
7095bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7096 VersionTuple CondVersion;
7097 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7098 CondVersion = E->getVersion();
7099
7100 // If we're using the '*' case here or if this check is redundant, then we
7101 // use the enclosing version to check both branches.
7102 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
7103 return Base::TraverseStmt(If->getThen()) &&
7104 Base::TraverseStmt(If->getElse());
7105 } else {
7106 // This isn't an availability checking 'if', we can just continue.
7107 return Base::TraverseIfStmt(If);
7108 }
7109
7110 AvailabilityStack.push_back(CondVersion);
7111 bool ShouldContinue = TraverseStmt(If->getThen());
7112 AvailabilityStack.pop_back();
7113
7114 return ShouldContinue && TraverseStmt(If->getElse());
7115}
7116
7117} // end anonymous namespace
7118
7119void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7120 Stmt *Body = nullptr;
7121
7122 if (auto *FD = D->getAsFunction()) {
7123 // FIXME: We only examine the pattern decl for availability violations now,
7124 // but we should also examine instantiated templates.
7125 if (FD->isTemplateInstantiation())
7126 return;
7127
7128 Body = FD->getBody();
7129 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7130 Body = MD->getBody();
7131
7132 assert(Body && "Need a body here!");
7133
Erik Pilkingtonf35114c2016-10-25 19:05:50 +00007134 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
Erik Pilkington5cd57172016-08-16 17:44:11 +00007135}