Bug Summary

File:tools/clang/lib/Sema/SemaDeclAttr.cpp
Location:line 5463, column 10
Description:Called C++ object pointer is null

Annotated Source Code

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