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/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/DelayedDiagnostic.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/MathExtras.h"
39
40 using namespace clang;
41 using namespace sema;
42
43 namespace AttributeLangSupport {
44 enum LANG {
45 C,
46 Cpp,
47 ObjC
48 };
49 } // end namespace AttributeLangSupport
50
51 //===----------------------------------------------------------------------===//
52 // Helper functions
53 //===----------------------------------------------------------------------===//
54
55 /// isFunctionOrMethod - Return true if the given decl has function
56 /// type (function or function-typed variable) or an Objective-C
57 /// method.
isFunctionOrMethod(const Decl * D)58 static bool isFunctionOrMethod(const Decl *D) {
59 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
60 }
61
62 /// Return true if the given decl has function type (function or
63 /// function-typed variable) or an Objective-C method or a block.
isFunctionOrMethodOrBlock(const Decl * D)64 static bool isFunctionOrMethodOrBlock(const Decl *D) {
65 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
66 }
67
68 /// Return true if the given decl has a declarator that should have
69 /// been processed by Sema::GetTypeForDeclarator.
hasDeclarator(const Decl * D)70 static bool hasDeclarator(const Decl *D) {
71 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
72 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
73 isa<ObjCPropertyDecl>(D);
74 }
75
76 /// hasFunctionProto - Return true if the given decl has a argument
77 /// information. This decl should have already passed
78 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
hasFunctionProto(const Decl * D)79 static bool hasFunctionProto(const Decl *D) {
80 if (const FunctionType *FnTy = D->getFunctionType())
81 return isa<FunctionProtoType>(FnTy);
82 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
83 }
84
85 /// getFunctionOrMethodNumParams - Return number of function or method
86 /// parameters. It is an error to call this on a K&R function (use
87 /// hasFunctionProto first).
getFunctionOrMethodNumParams(const Decl * D)88 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
89 if (const FunctionType *FnTy = D->getFunctionType())
90 return cast<FunctionProtoType>(FnTy)->getNumParams();
91 if (const auto *BD = dyn_cast<BlockDecl>(D))
92 return BD->getNumParams();
93 return cast<ObjCMethodDecl>(D)->param_size();
94 }
95
getFunctionOrMethodParam(const Decl * D,unsigned Idx)96 static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
97 unsigned Idx) {
98 if (const auto *FD = dyn_cast<FunctionDecl>(D))
99 return FD->getParamDecl(Idx);
100 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
101 return MD->getParamDecl(Idx);
102 if (const auto *BD = dyn_cast<BlockDecl>(D))
103 return BD->getParamDecl(Idx);
104 return nullptr;
105 }
106
getFunctionOrMethodParamType(const Decl * D,unsigned Idx)107 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
108 if (const FunctionType *FnTy = D->getFunctionType())
109 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
110 if (const auto *BD = dyn_cast<BlockDecl>(D))
111 return BD->getParamDecl(Idx)->getType();
112
113 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
114 }
115
getFunctionOrMethodParamRange(const Decl * D,unsigned Idx)116 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
117 if (auto *PVD = getFunctionOrMethodParam(D, Idx))
118 return PVD->getSourceRange();
119 return SourceRange();
120 }
121
getFunctionOrMethodResultType(const Decl * D)122 static QualType getFunctionOrMethodResultType(const Decl *D) {
123 if (const FunctionType *FnTy = D->getFunctionType())
124 return FnTy->getReturnType();
125 return cast<ObjCMethodDecl>(D)->getReturnType();
126 }
127
getFunctionOrMethodResultSourceRange(const Decl * D)128 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
129 if (const auto *FD = dyn_cast<FunctionDecl>(D))
130 return FD->getReturnTypeSourceRange();
131 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
132 return MD->getReturnTypeSourceRange();
133 return SourceRange();
134 }
135
isFunctionOrMethodVariadic(const Decl * D)136 static bool isFunctionOrMethodVariadic(const Decl *D) {
137 if (const FunctionType *FnTy = D->getFunctionType())
138 return cast<FunctionProtoType>(FnTy)->isVariadic();
139 if (const auto *BD = dyn_cast<BlockDecl>(D))
140 return BD->isVariadic();
141 return cast<ObjCMethodDecl>(D)->isVariadic();
142 }
143
isInstanceMethod(const Decl * D)144 static bool isInstanceMethod(const Decl *D) {
145 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
146 return MethodDecl->isInstance();
147 return false;
148 }
149
isNSStringType(QualType T,ASTContext & Ctx)150 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
151 const auto *PT = T->getAs<ObjCObjectPointerType>();
152 if (!PT)
153 return false;
154
155 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
156 if (!Cls)
157 return false;
158
159 IdentifierInfo* ClsName = Cls->getIdentifier();
160
161 // FIXME: Should we walk the chain of classes?
162 return ClsName == &Ctx.Idents.get("NSString") ||
163 ClsName == &Ctx.Idents.get("NSMutableString");
164 }
165
isCFStringType(QualType T,ASTContext & Ctx)166 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
167 const auto *PT = T->getAs<PointerType>();
168 if (!PT)
169 return false;
170
171 const auto *RT = PT->getPointeeType()->getAs<RecordType>();
172 if (!RT)
173 return false;
174
175 const RecordDecl *RD = RT->getDecl();
176 if (RD->getTagKind() != TTK_Struct)
177 return false;
178
179 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
180 }
181
getNumAttributeArgs(const ParsedAttr & AL)182 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
183 // FIXME: Include the type in the argument list.
184 return AL.getNumArgs() + AL.hasParsedType();
185 }
186
187 template <typename Compare>
checkAttributeNumArgsImpl(Sema & S,const ParsedAttr & AL,unsigned Num,unsigned Diag,Compare Comp)188 static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
189 unsigned Num, unsigned Diag,
190 Compare Comp) {
191 if (Comp(getNumAttributeArgs(AL), Num)) {
192 S.Diag(AL.getLoc(), Diag) << AL << Num;
193 return false;
194 }
195
196 return true;
197 }
198
199 /// Check if the attribute has exactly as many args as Num. May
200 /// output an error.
checkAttributeNumArgs(Sema & S,const ParsedAttr & AL,unsigned Num)201 static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
202 return checkAttributeNumArgsImpl(S, AL, Num,
203 diag::err_attribute_wrong_number_arguments,
204 std::not_equal_to<unsigned>());
205 }
206
207 /// Check if the attribute has at least as many args as Num. May
208 /// output an error.
checkAttributeAtLeastNumArgs(Sema & S,const ParsedAttr & AL,unsigned Num)209 static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
210 unsigned Num) {
211 return checkAttributeNumArgsImpl(S, AL, Num,
212 diag::err_attribute_too_few_arguments,
213 std::less<unsigned>());
214 }
215
216 /// Check if the attribute has at most as many args as Num. May
217 /// output an error.
checkAttributeAtMostNumArgs(Sema & S,const ParsedAttr & AL,unsigned Num)218 static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
219 unsigned Num) {
220 return checkAttributeNumArgsImpl(S, AL, Num,
221 diag::err_attribute_too_many_arguments,
222 std::greater<unsigned>());
223 }
224
225 /// A helper function to provide Attribute Location for the Attr types
226 /// AND the ParsedAttr.
227 template <typename AttrInfo>
228 static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
229 SourceLocation>::type
getAttrLoc(const AttrInfo & AL)230 getAttrLoc(const AttrInfo &AL) {
231 return AL.getLocation();
232 }
getAttrLoc(const ParsedAttr & AL)233 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
234
235 /// If Expr is a valid integer constant, get the value of the integer
236 /// expression and return success or failure. May output an error.
237 ///
238 /// Negative argument is implicitly converted to unsigned, unless
239 /// \p StrictlyUnsigned is true.
240 template <typename AttrInfo>
checkUInt32Argument(Sema & S,const AttrInfo & AI,const Expr * Expr,uint32_t & Val,unsigned Idx=UINT_MAX,bool StrictlyUnsigned=false)241 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
242 uint32_t &Val, unsigned Idx = UINT_MAX,
243 bool StrictlyUnsigned = false) {
244 llvm::APSInt I(32);
245 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
246 !Expr->isIntegerConstantExpr(I, S.Context)) {
247 if (Idx != UINT_MAX)
248 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
249 << AI << Idx << AANT_ArgumentIntegerConstant
250 << Expr->getSourceRange();
251 else
252 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
253 << AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
254 return false;
255 }
256
257 if (!I.isIntN(32)) {
258 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
259 << I.toString(10, false) << 32 << /* Unsigned */ 1;
260 return false;
261 }
262
263 if (StrictlyUnsigned && I.isSigned() && I.isNegative()) {
264 S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
265 << AI << /*non-negative*/ 1;
266 return false;
267 }
268
269 Val = (uint32_t)I.getZExtValue();
270 return true;
271 }
272
273 /// Wrapper around checkUInt32Argument, with an extra check to be sure
274 /// that the result will fit into a regular (signed) int. All args have the same
275 /// purpose as they do in checkUInt32Argument.
276 template <typename AttrInfo>
checkPositiveIntArgument(Sema & S,const AttrInfo & AI,const Expr * Expr,int & Val,unsigned Idx=UINT_MAX)277 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
278 int &Val, unsigned Idx = UINT_MAX) {
279 uint32_t UVal;
280 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
281 return false;
282
283 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
284 llvm::APSInt I(32); // for toString
285 I = UVal;
286 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
287 << I.toString(10, false) << 32 << /* Unsigned */ 0;
288 return false;
289 }
290
291 Val = UVal;
292 return true;
293 }
294
295 /// Diagnose mutually exclusive attributes when present on a given
296 /// declaration. Returns true if diagnosed.
297 template <typename AttrTy>
checkAttrMutualExclusion(Sema & S,Decl * D,const ParsedAttr & AL)298 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
299 if (const auto *A = D->getAttr<AttrTy>()) {
300 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
301 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
302 return true;
303 }
304 return false;
305 }
306
307 template <typename AttrTy>
checkAttrMutualExclusion(Sema & S,Decl * D,const Attr & AL)308 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
309 if (const auto *A = D->getAttr<AttrTy>()) {
310 S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
311 << A;
312 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
313 return true;
314 }
315 return false;
316 }
317
318 /// Check if IdxExpr is a valid parameter index for a function or
319 /// instance method D. May output an error.
320 ///
321 /// \returns true if IdxExpr is a valid index.
322 template <typename AttrInfo>
checkFunctionOrMethodParameterIndex(Sema & S,const Decl * D,const AttrInfo & AI,unsigned AttrArgNum,const Expr * IdxExpr,ParamIdx & Idx,bool CanIndexImplicitThis=false)323 static bool checkFunctionOrMethodParameterIndex(
324 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
325 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
326 assert(isFunctionOrMethodOrBlock(D));
327
328 // In C++ the implicit 'this' function parameter also counts.
329 // Parameters are counted from one.
330 bool HP = hasFunctionProto(D);
331 bool HasImplicitThisParam = isInstanceMethod(D);
332 bool IV = HP && isFunctionOrMethodVariadic(D);
333 unsigned NumParams =
334 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
335
336 llvm::APSInt IdxInt;
337 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
338 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
339 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
340 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
341 << IdxExpr->getSourceRange();
342 return false;
343 }
344
345 unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX);
346 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
347 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
348 << &AI << AttrArgNum << IdxExpr->getSourceRange();
349 return false;
350 }
351 if (HasImplicitThisParam && !CanIndexImplicitThis) {
352 if (IdxSource == 1) {
353 S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
354 << &AI << IdxExpr->getSourceRange();
355 return false;
356 }
357 }
358
359 Idx = ParamIdx(IdxSource, D);
360 return true;
361 }
362
363 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
364 /// If not emit an error and return false. If the argument is an identifier it
365 /// will emit an error with a fixit hint and treat it as if it was a string
366 /// literal.
checkStringLiteralArgumentAttr(const ParsedAttr & AL,unsigned ArgNum,StringRef & Str,SourceLocation * ArgLocation)367 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
368 StringRef &Str,
369 SourceLocation *ArgLocation) {
370 // Look for identifiers. If we have one emit a hint to fix it to a literal.
371 if (AL.isArgIdent(ArgNum)) {
372 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
373 Diag(Loc->Loc, diag::err_attribute_argument_type)
374 << AL << AANT_ArgumentString
375 << FixItHint::CreateInsertion(Loc->Loc, "\"")
376 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
377 Str = Loc->Ident->getName();
378 if (ArgLocation)
379 *ArgLocation = Loc->Loc;
380 return true;
381 }
382
383 // Now check for an actual string literal.
384 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
385 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
386 if (ArgLocation)
387 *ArgLocation = ArgExpr->getBeginLoc();
388
389 if (!Literal || !Literal->isAscii()) {
390 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
391 << AL << AANT_ArgumentString;
392 return false;
393 }
394
395 Str = Literal->getString();
396 return true;
397 }
398
399 /// Applies the given attribute to the Decl without performing any
400 /// additional semantic checking.
401 template <typename AttrType>
handleSimpleAttribute(Sema & S,Decl * D,SourceRange SR,unsigned SpellingIndex)402 static void handleSimpleAttribute(Sema &S, Decl *D, SourceRange SR,
403 unsigned SpellingIndex) {
404 D->addAttr(::new (S.Context) AttrType(SR, S.Context, SpellingIndex));
405 }
406
407 template <typename AttrType>
handleSimpleAttribute(Sema & S,Decl * D,const ParsedAttr & AL)408 static void handleSimpleAttribute(Sema &S, Decl *D, const ParsedAttr &AL) {
409 handleSimpleAttribute<AttrType>(S, D, AL.getRange(),
410 AL.getAttributeSpellingListIndex());
411 }
412
413
414 template <typename... DiagnosticArgs>
415 static const Sema::SemaDiagnosticBuilder&
appendDiagnostics(const Sema::SemaDiagnosticBuilder & Bldr)416 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
417 return Bldr;
418 }
419
420 template <typename T, typename... DiagnosticArgs>
421 static const Sema::SemaDiagnosticBuilder&
appendDiagnostics(const Sema::SemaDiagnosticBuilder & Bldr,T && ExtraArg,DiagnosticArgs &&...ExtraArgs)422 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
423 DiagnosticArgs &&... ExtraArgs) {
424 return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
425 std::forward<DiagnosticArgs>(ExtraArgs)...);
426 }
427
428 /// Add an attribute {@code AttrType} to declaration {@code D}, provided that
429 /// {@code PassesCheck} is true.
430 /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
431 /// specified in {@code ExtraArgs}.
432 template <typename AttrType, typename... DiagnosticArgs>
433 static void
handleSimpleAttributeOrDiagnose(Sema & S,Decl * D,SourceRange SR,unsigned SpellingIndex,bool PassesCheck,unsigned DiagID,DiagnosticArgs &&...ExtraArgs)434 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR,
435 unsigned SpellingIndex,
436 bool PassesCheck,
437 unsigned DiagID, DiagnosticArgs&&... ExtraArgs) {
438 if (!PassesCheck) {
439 Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
440 appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
441 return;
442 }
443 handleSimpleAttribute<AttrType>(S, D, SR, SpellingIndex);
444 }
445
446 template <typename AttrType, typename... DiagnosticArgs>
447 static void
handleSimpleAttributeOrDiagnose(Sema & S,Decl * D,const ParsedAttr & AL,bool PassesCheck,unsigned DiagID,DiagnosticArgs &&...ExtraArgs)448 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, const ParsedAttr &AL,
449 bool PassesCheck,
450 unsigned DiagID,
451 DiagnosticArgs&&... ExtraArgs) {
452 return handleSimpleAttributeOrDiagnose<AttrType>(
453 S, D, AL.getRange(), AL.getAttributeSpellingListIndex(), PassesCheck,
454 DiagID, std::forward<DiagnosticArgs>(ExtraArgs)...);
455 }
456
457 template <typename AttrType>
handleSimpleAttributeWithExclusions(Sema & S,Decl * D,const ParsedAttr & AL)458 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
459 const ParsedAttr &AL) {
460 handleSimpleAttribute<AttrType>(S, D, AL);
461 }
462
463 /// Applies the given attribute to the Decl so long as the Decl doesn't
464 /// already have one of the given incompatible attributes.
465 template <typename AttrType, typename IncompatibleAttrType,
466 typename... IncompatibleAttrTypes>
handleSimpleAttributeWithExclusions(Sema & S,Decl * D,const ParsedAttr & AL)467 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
468 const ParsedAttr &AL) {
469 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
470 return;
471 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
472 AL);
473 }
474
475 /// Check if the passed-in expression is of type int or bool.
isIntOrBool(Expr * Exp)476 static bool isIntOrBool(Expr *Exp) {
477 QualType QT = Exp->getType();
478 return QT->isBooleanType() || QT->isIntegerType();
479 }
480
481
482 // Check to see if the type is a smart pointer of some kind. We assume
483 // it's a smart pointer if it defines both operator-> and operator*.
threadSafetyCheckIsSmartPointer(Sema & S,const RecordType * RT)484 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
485 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
486 OverloadedOperatorKind Op) {
487 DeclContextLookupResult Result =
488 Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
489 return !Result.empty();
490 };
491
492 const RecordDecl *Record = RT->getDecl();
493 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
494 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
495 if (foundStarOperator && foundArrowOperator)
496 return true;
497
498 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
499 if (!CXXRecord)
500 return false;
501
502 for (auto BaseSpecifier : CXXRecord->bases()) {
503 if (!foundStarOperator)
504 foundStarOperator = IsOverloadedOperatorPresent(
505 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
506 if (!foundArrowOperator)
507 foundArrowOperator = IsOverloadedOperatorPresent(
508 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
509 }
510
511 if (foundStarOperator && foundArrowOperator)
512 return true;
513
514 return false;
515 }
516
517 /// Check if passed in Decl is a pointer type.
518 /// Note that this function may produce an error message.
519 /// \return true if the Decl is a pointer type; false otherwise
threadSafetyCheckIsPointer(Sema & S,const Decl * D,const ParsedAttr & AL)520 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
521 const ParsedAttr &AL) {
522 const auto *VD = cast<ValueDecl>(D);
523 QualType QT = VD->getType();
524 if (QT->isAnyPointerType())
525 return true;
526
527 if (const auto *RT = QT->getAs<RecordType>()) {
528 // If it's an incomplete type, it could be a smart pointer; skip it.
529 // (We don't want to force template instantiation if we can avoid it,
530 // since that would alter the order in which templates are instantiated.)
531 if (RT->isIncompleteType())
532 return true;
533
534 if (threadSafetyCheckIsSmartPointer(S, RT))
535 return true;
536 }
537
538 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
539 return false;
540 }
541
542 /// Checks that the passed in QualType either is of RecordType or points
543 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
getRecordType(QualType QT)544 static const RecordType *getRecordType(QualType QT) {
545 if (const auto *RT = QT->getAs<RecordType>())
546 return RT;
547
548 // Now check if we point to record type.
549 if (const auto *PT = QT->getAs<PointerType>())
550 return PT->getPointeeType()->getAs<RecordType>();
551
552 return nullptr;
553 }
554
555 template <typename AttrType>
checkRecordDeclForAttr(const RecordDecl * RD)556 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
557 // Check if the record itself has the attribute.
558 if (RD->hasAttr<AttrType>())
559 return true;
560
561 // Else check if any base classes have the attribute.
562 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
563 CXXBasePaths BPaths(false, false);
564 if (CRD->lookupInBases(
565 [](const CXXBaseSpecifier *BS, CXXBasePath &) {
566 const auto &Ty = *BS->getType();
567 // If it's type-dependent, we assume it could have the attribute.
568 if (Ty.isDependentType())
569 return true;
570 return Ty.getAs<RecordType>()->getDecl()->hasAttr<AttrType>();
571 },
572 BPaths, true))
573 return true;
574 }
575 return false;
576 }
577
checkRecordTypeForCapability(Sema & S,QualType Ty)578 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
579 const RecordType *RT = getRecordType(Ty);
580
581 if (!RT)
582 return false;
583
584 // Don't check for the capability if the class hasn't been defined yet.
585 if (RT->isIncompleteType())
586 return true;
587
588 // Allow smart pointers to be used as capability objects.
589 // FIXME -- Check the type that the smart pointer points to.
590 if (threadSafetyCheckIsSmartPointer(S, RT))
591 return true;
592
593 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
594 }
595
checkTypedefTypeForCapability(QualType Ty)596 static bool checkTypedefTypeForCapability(QualType Ty) {
597 const auto *TD = Ty->getAs<TypedefType>();
598 if (!TD)
599 return false;
600
601 TypedefNameDecl *TN = TD->getDecl();
602 if (!TN)
603 return false;
604
605 return TN->hasAttr<CapabilityAttr>();
606 }
607
typeHasCapability(Sema & S,QualType Ty)608 static bool typeHasCapability(Sema &S, QualType Ty) {
609 if (checkTypedefTypeForCapability(Ty))
610 return true;
611
612 if (checkRecordTypeForCapability(S, Ty))
613 return true;
614
615 return false;
616 }
617
isCapabilityExpr(Sema & S,const Expr * Ex)618 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
619 // Capability expressions are simple expressions involving the boolean logic
620 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
621 // a DeclRefExpr is found, its type should be checked to determine whether it
622 // is a capability or not.
623
624 if (const auto *E = dyn_cast<CastExpr>(Ex))
625 return isCapabilityExpr(S, E->getSubExpr());
626 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
627 return isCapabilityExpr(S, E->getSubExpr());
628 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
629 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
630 E->getOpcode() == UO_Deref)
631 return isCapabilityExpr(S, E->getSubExpr());
632 return false;
633 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
634 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
635 return isCapabilityExpr(S, E->getLHS()) &&
636 isCapabilityExpr(S, E->getRHS());
637 return false;
638 }
639
640 return typeHasCapability(S, Ex->getType());
641 }
642
643 /// Checks that all attribute arguments, starting from Sidx, resolve to
644 /// a capability object.
645 /// \param Sidx The attribute argument index to start checking with.
646 /// \param ParamIdxOk Whether an argument can be indexing into a function
647 /// parameter list.
checkAttrArgsAreCapabilityObjs(Sema & S,Decl * D,const ParsedAttr & AL,SmallVectorImpl<Expr * > & Args,unsigned Sidx=0,bool ParamIdxOk=false)648 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
649 const ParsedAttr &AL,
650 SmallVectorImpl<Expr *> &Args,
651 unsigned Sidx = 0,
652 bool ParamIdxOk = false) {
653 if (Sidx == AL.getNumArgs()) {
654 // If we don't have any capability arguments, the attribute implicitly
655 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
656 // a non-static method, and that the class is a (scoped) capability.
657 const auto *MD = dyn_cast<const CXXMethodDecl>(D);
658 if (MD && !MD->isStatic()) {
659 const CXXRecordDecl *RD = MD->getParent();
660 // FIXME -- need to check this again on template instantiation
661 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
662 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
663 S.Diag(AL.getLoc(),
664 diag::warn_thread_attribute_not_on_capability_member)
665 << AL << MD->getParent();
666 } else {
667 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
668 << AL;
669 }
670 }
671
672 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
673 Expr *ArgExp = AL.getArgAsExpr(Idx);
674
675 if (ArgExp->isTypeDependent()) {
676 // FIXME -- need to check this again on template instantiation
677 Args.push_back(ArgExp);
678 continue;
679 }
680
681 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
682 if (StrLit->getLength() == 0 ||
683 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
684 // Pass empty strings to the analyzer without warnings.
685 // Treat "*" as the universal lock.
686 Args.push_back(ArgExp);
687 continue;
688 }
689
690 // We allow constant strings to be used as a placeholder for expressions
691 // that are not valid C++ syntax, but warn that they are ignored.
692 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
693 Args.push_back(ArgExp);
694 continue;
695 }
696
697 QualType ArgTy = ArgExp->getType();
698
699 // A pointer to member expression of the form &MyClass::mu is treated
700 // specially -- we need to look at the type of the member.
701 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
702 if (UOp->getOpcode() == UO_AddrOf)
703 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
704 if (DRE->getDecl()->isCXXInstanceMember())
705 ArgTy = DRE->getDecl()->getType();
706
707 // First see if we can just cast to record type, or pointer to record type.
708 const RecordType *RT = getRecordType(ArgTy);
709
710 // Now check if we index into a record type function param.
711 if(!RT && ParamIdxOk) {
712 const auto *FD = dyn_cast<FunctionDecl>(D);
713 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
714 if(FD && IL) {
715 unsigned int NumParams = FD->getNumParams();
716 llvm::APInt ArgValue = IL->getValue();
717 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
718 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
719 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
720 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
721 << AL << Idx + 1 << NumParams;
722 continue;
723 }
724 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
725 }
726 }
727
728 // If the type does not have a capability, see if the components of the
729 // expression have capabilities. This allows for writing C code where the
730 // capability may be on the type, and the expression is a capability
731 // boolean logic expression. Eg) requires_capability(A || B && !C)
732 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
733 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
734 << AL << ArgTy;
735
736 Args.push_back(ArgExp);
737 }
738 }
739
740 //===----------------------------------------------------------------------===//
741 // Attribute Implementations
742 //===----------------------------------------------------------------------===//
743
handlePtGuardedVarAttr(Sema & S,Decl * D,const ParsedAttr & AL)744 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
745 if (!threadSafetyCheckIsPointer(S, D, AL))
746 return;
747
748 D->addAttr(::new (S.Context)
749 PtGuardedVarAttr(AL.getRange(), S.Context,
750 AL.getAttributeSpellingListIndex()));
751 }
752
checkGuardedByAttrCommon(Sema & S,Decl * D,const ParsedAttr & AL,Expr * & Arg)753 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
754 Expr *&Arg) {
755 SmallVector<Expr *, 1> Args;
756 // check that all arguments are lockable objects
757 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
758 unsigned Size = Args.size();
759 if (Size != 1)
760 return false;
761
762 Arg = Args[0];
763
764 return true;
765 }
766
handleGuardedByAttr(Sema & S,Decl * D,const ParsedAttr & AL)767 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
768 Expr *Arg = nullptr;
769 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
770 return;
771
772 D->addAttr(::new (S.Context) GuardedByAttr(
773 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
774 }
775
handlePtGuardedByAttr(Sema & S,Decl * D,const ParsedAttr & AL)776 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
777 Expr *Arg = nullptr;
778 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
779 return;
780
781 if (!threadSafetyCheckIsPointer(S, D, AL))
782 return;
783
784 D->addAttr(::new (S.Context) PtGuardedByAttr(
785 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
786 }
787
checkAcquireOrderAttrCommon(Sema & S,Decl * D,const ParsedAttr & AL,SmallVectorImpl<Expr * > & Args)788 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
789 SmallVectorImpl<Expr *> &Args) {
790 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
791 return false;
792
793 // Check that this attribute only applies to lockable types.
794 QualType QT = cast<ValueDecl>(D)->getType();
795 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
796 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
797 return false;
798 }
799
800 // Check that all arguments are lockable objects.
801 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
802 if (Args.empty())
803 return false;
804
805 return true;
806 }
807
handleAcquiredAfterAttr(Sema & S,Decl * D,const ParsedAttr & AL)808 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
809 SmallVector<Expr *, 1> Args;
810 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
811 return;
812
813 Expr **StartArg = &Args[0];
814 D->addAttr(::new (S.Context) AcquiredAfterAttr(
815 AL.getRange(), S.Context, StartArg, Args.size(),
816 AL.getAttributeSpellingListIndex()));
817 }
818
handleAcquiredBeforeAttr(Sema & S,Decl * D,const ParsedAttr & AL)819 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
820 SmallVector<Expr *, 1> Args;
821 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
822 return;
823
824 Expr **StartArg = &Args[0];
825 D->addAttr(::new (S.Context) AcquiredBeforeAttr(
826 AL.getRange(), S.Context, StartArg, Args.size(),
827 AL.getAttributeSpellingListIndex()));
828 }
829
checkLockFunAttrCommon(Sema & S,Decl * D,const ParsedAttr & AL,SmallVectorImpl<Expr * > & Args)830 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
831 SmallVectorImpl<Expr *> &Args) {
832 // zero or more arguments ok
833 // check that all arguments are lockable objects
834 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
835
836 return true;
837 }
838
handleAssertSharedLockAttr(Sema & S,Decl * D,const ParsedAttr & AL)839 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
840 SmallVector<Expr *, 1> Args;
841 if (!checkLockFunAttrCommon(S, D, AL, Args))
842 return;
843
844 unsigned Size = Args.size();
845 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
846 D->addAttr(::new (S.Context)
847 AssertSharedLockAttr(AL.getRange(), S.Context, StartArg, Size,
848 AL.getAttributeSpellingListIndex()));
849 }
850
handleAssertExclusiveLockAttr(Sema & S,Decl * D,const ParsedAttr & AL)851 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
852 const ParsedAttr &AL) {
853 SmallVector<Expr *, 1> Args;
854 if (!checkLockFunAttrCommon(S, D, AL, Args))
855 return;
856
857 unsigned Size = Args.size();
858 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
859 D->addAttr(::new (S.Context) AssertExclusiveLockAttr(
860 AL.getRange(), S.Context, StartArg, Size,
861 AL.getAttributeSpellingListIndex()));
862 }
863
864 /// Checks to be sure that the given parameter number is in bounds, and
865 /// is an integral type. Will emit appropriate diagnostics if this returns
866 /// false.
867 ///
868 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
869 template <typename AttrInfo>
checkParamIsIntegerType(Sema & S,const FunctionDecl * FD,const AttrInfo & AI,unsigned AttrArgNo)870 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
871 const AttrInfo &AI, unsigned AttrArgNo) {
872 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
873 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
874 ParamIdx Idx;
875 if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
876 Idx))
877 return false;
878
879 const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
880 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
881 SourceLocation SrcLoc = AttrArg->getBeginLoc();
882 S.Diag(SrcLoc, diag::err_attribute_integers_only)
883 << AI << Param->getSourceRange();
884 return false;
885 }
886 return true;
887 }
888
handleAllocSizeAttr(Sema & S,Decl * D,const ParsedAttr & AL)889 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
890 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
891 !checkAttributeAtMostNumArgs(S, AL, 2))
892 return;
893
894 const auto *FD = cast<FunctionDecl>(D);
895 if (!FD->getReturnType()->isPointerType()) {
896 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
897 return;
898 }
899
900 const Expr *SizeExpr = AL.getArgAsExpr(0);
901 int SizeArgNoVal;
902 // Parameter indices are 1-indexed, hence Index=1
903 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Index=*/1))
904 return;
905 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
906 return;
907 ParamIdx SizeArgNo(SizeArgNoVal, D);
908
909 ParamIdx NumberArgNo;
910 if (AL.getNumArgs() == 2) {
911 const Expr *NumberExpr = AL.getArgAsExpr(1);
912 int Val;
913 // Parameter indices are 1-based, hence Index=2
914 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Index=*/2))
915 return;
916 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
917 return;
918 NumberArgNo = ParamIdx(Val, D);
919 }
920
921 D->addAttr(::new (S.Context)
922 AllocSizeAttr(AL.getRange(), S.Context, SizeArgNo, NumberArgNo,
923 AL.getAttributeSpellingListIndex()));
924 }
925
checkTryLockFunAttrCommon(Sema & S,Decl * D,const ParsedAttr & AL,SmallVectorImpl<Expr * > & Args)926 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
927 SmallVectorImpl<Expr *> &Args) {
928 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
929 return false;
930
931 if (!isIntOrBool(AL.getArgAsExpr(0))) {
932 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
933 << AL << 1 << AANT_ArgumentIntOrBool;
934 return false;
935 }
936
937 // check that all arguments are lockable objects
938 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
939
940 return true;
941 }
942
handleSharedTrylockFunctionAttr(Sema & S,Decl * D,const ParsedAttr & AL)943 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
944 const ParsedAttr &AL) {
945 SmallVector<Expr*, 2> Args;
946 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
947 return;
948
949 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
950 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(),
951 AL.getAttributeSpellingListIndex()));
952 }
953
handleExclusiveTrylockFunctionAttr(Sema & S,Decl * D,const ParsedAttr & AL)954 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
955 const ParsedAttr &AL) {
956 SmallVector<Expr*, 2> Args;
957 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
958 return;
959
960 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
961 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(),
962 Args.size(), AL.getAttributeSpellingListIndex()));
963 }
964
handleLockReturnedAttr(Sema & S,Decl * D,const ParsedAttr & AL)965 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
966 // check that the argument is lockable object
967 SmallVector<Expr*, 1> Args;
968 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
969 unsigned Size = Args.size();
970 if (Size == 0)
971 return;
972
973 D->addAttr(::new (S.Context)
974 LockReturnedAttr(AL.getRange(), S.Context, Args[0],
975 AL.getAttributeSpellingListIndex()));
976 }
977
handleLocksExcludedAttr(Sema & S,Decl * D,const ParsedAttr & AL)978 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
979 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
980 return;
981
982 // check that all arguments are lockable objects
983 SmallVector<Expr*, 1> Args;
984 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
985 unsigned Size = Args.size();
986 if (Size == 0)
987 return;
988 Expr **StartArg = &Args[0];
989
990 D->addAttr(::new (S.Context)
991 LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size,
992 AL.getAttributeSpellingListIndex()));
993 }
994
checkFunctionConditionAttr(Sema & S,Decl * D,const ParsedAttr & AL,Expr * & Cond,StringRef & Msg)995 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
996 Expr *&Cond, StringRef &Msg) {
997 Cond = AL.getArgAsExpr(0);
998 if (!Cond->isTypeDependent()) {
999 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
1000 if (Converted.isInvalid())
1001 return false;
1002 Cond = Converted.get();
1003 }
1004
1005 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
1006 return false;
1007
1008 if (Msg.empty())
1009 Msg = "<no message provided>";
1010
1011 SmallVector<PartialDiagnosticAt, 8> Diags;
1012 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
1013 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
1014 Diags)) {
1015 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
1016 for (const PartialDiagnosticAt &PDiag : Diags)
1017 S.Diag(PDiag.first, PDiag.second);
1018 return false;
1019 }
1020 return true;
1021 }
1022
handleEnableIfAttr(Sema & S,Decl * D,const ParsedAttr & AL)1023 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1024 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
1025
1026 Expr *Cond;
1027 StringRef Msg;
1028 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1029 D->addAttr(::new (S.Context)
1030 EnableIfAttr(AL.getRange(), S.Context, Cond, Msg,
1031 AL.getAttributeSpellingListIndex()));
1032 }
1033
1034 namespace {
1035 /// Determines if a given Expr references any of the given function's
1036 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1037 class ArgumentDependenceChecker
1038 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1039 #ifndef NDEBUG
1040 const CXXRecordDecl *ClassType;
1041 #endif
1042 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
1043 bool Result;
1044
1045 public:
ArgumentDependenceChecker(const FunctionDecl * FD)1046 ArgumentDependenceChecker(const FunctionDecl *FD) {
1047 #ifndef NDEBUG
1048 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1049 ClassType = MD->getParent();
1050 else
1051 ClassType = nullptr;
1052 #endif
1053 Parms.insert(FD->param_begin(), FD->param_end());
1054 }
1055
referencesArgs(Expr * E)1056 bool referencesArgs(Expr *E) {
1057 Result = false;
1058 TraverseStmt(E);
1059 return Result;
1060 }
1061
VisitCXXThisExpr(CXXThisExpr * E)1062 bool VisitCXXThisExpr(CXXThisExpr *E) {
1063 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1064 "`this` doesn't refer to the enclosing class?");
1065 Result = true;
1066 return false;
1067 }
1068
VisitDeclRefExpr(DeclRefExpr * DRE)1069 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1070 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1071 if (Parms.count(PVD)) {
1072 Result = true;
1073 return false;
1074 }
1075 return true;
1076 }
1077 };
1078 }
1079
handleDiagnoseIfAttr(Sema & S,Decl * D,const ParsedAttr & AL)1080 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1081 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1082
1083 Expr *Cond;
1084 StringRef Msg;
1085 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1086 return;
1087
1088 StringRef DiagTypeStr;
1089 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1090 return;
1091
1092 DiagnoseIfAttr::DiagnosticType DiagType;
1093 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1094 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1095 diag::err_diagnose_if_invalid_diagnostic_type);
1096 return;
1097 }
1098
1099 bool ArgDependent = false;
1100 if (const auto *FD = dyn_cast<FunctionDecl>(D))
1101 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1102 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1103 AL.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent,
1104 cast<NamedDecl>(D), AL.getAttributeSpellingListIndex()));
1105 }
1106
handlePassObjectSizeAttr(Sema & S,Decl * D,const ParsedAttr & AL)1107 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1108 if (D->hasAttr<PassObjectSizeAttr>()) {
1109 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1110 return;
1111 }
1112
1113 Expr *E = AL.getArgAsExpr(0);
1114 uint32_t Type;
1115 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1116 return;
1117
1118 // pass_object_size's argument is passed in as the second argument of
1119 // __builtin_object_size. So, it has the same constraints as that second
1120 // argument; namely, it must be in the range [0, 3].
1121 if (Type > 3) {
1122 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_outof_range)
1123 << AL << 0 << 3 << E->getSourceRange();
1124 return;
1125 }
1126
1127 // pass_object_size is only supported on constant pointer parameters; as a
1128 // kindness to users, we allow the parameter to be non-const for declarations.
1129 // At this point, we have no clue if `D` belongs to a function declaration or
1130 // definition, so we defer the constness check until later.
1131 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1132 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1133 return;
1134 }
1135
1136 D->addAttr(::new (S.Context) PassObjectSizeAttr(
1137 AL.getRange(), S.Context, (int)Type, AL.getAttributeSpellingListIndex()));
1138 }
1139
handleConsumableAttr(Sema & S,Decl * D,const ParsedAttr & AL)1140 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1141 ConsumableAttr::ConsumedState DefaultState;
1142
1143 if (AL.isArgIdent(0)) {
1144 IdentifierLoc *IL = AL.getArgAsIdent(0);
1145 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1146 DefaultState)) {
1147 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1148 << IL->Ident;
1149 return;
1150 }
1151 } else {
1152 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1153 << AL << AANT_ArgumentIdentifier;
1154 return;
1155 }
1156
1157 D->addAttr(::new (S.Context)
1158 ConsumableAttr(AL.getRange(), S.Context, DefaultState,
1159 AL.getAttributeSpellingListIndex()));
1160 }
1161
checkForConsumableClass(Sema & S,const CXXMethodDecl * MD,const ParsedAttr & AL)1162 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1163 const ParsedAttr &AL) {
1164 QualType ThisType = MD->getThisType()->getPointeeType();
1165
1166 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1167 if (!RD->hasAttr<ConsumableAttr>()) {
1168 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1169 RD->getNameAsString();
1170
1171 return false;
1172 }
1173 }
1174
1175 return true;
1176 }
1177
handleCallableWhenAttr(Sema & S,Decl * D,const ParsedAttr & AL)1178 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1179 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1180 return;
1181
1182 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1183 return;
1184
1185 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1186 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1187 CallableWhenAttr::ConsumedState CallableState;
1188
1189 StringRef StateString;
1190 SourceLocation Loc;
1191 if (AL.isArgIdent(ArgIndex)) {
1192 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1193 StateString = Ident->Ident->getName();
1194 Loc = Ident->Loc;
1195 } else {
1196 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1197 return;
1198 }
1199
1200 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1201 CallableState)) {
1202 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1203 return;
1204 }
1205
1206 States.push_back(CallableState);
1207 }
1208
1209 D->addAttr(::new (S.Context)
1210 CallableWhenAttr(AL.getRange(), S.Context, States.data(),
1211 States.size(), AL.getAttributeSpellingListIndex()));
1212 }
1213
handleParamTypestateAttr(Sema & S,Decl * D,const ParsedAttr & AL)1214 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1215 ParamTypestateAttr::ConsumedState ParamState;
1216
1217 if (AL.isArgIdent(0)) {
1218 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1219 StringRef StateString = Ident->Ident->getName();
1220
1221 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1222 ParamState)) {
1223 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1224 << AL << StateString;
1225 return;
1226 }
1227 } else {
1228 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1229 << AL << AANT_ArgumentIdentifier;
1230 return;
1231 }
1232
1233 // FIXME: This check is currently being done in the analysis. It can be
1234 // enabled here only after the parser propagates attributes at
1235 // template specialization definition, not declaration.
1236 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1237 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1238 //
1239 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1240 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1241 // ReturnType.getAsString();
1242 // return;
1243 //}
1244
1245 D->addAttr(::new (S.Context)
1246 ParamTypestateAttr(AL.getRange(), S.Context, ParamState,
1247 AL.getAttributeSpellingListIndex()));
1248 }
1249
handleReturnTypestateAttr(Sema & S,Decl * D,const ParsedAttr & AL)1250 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1251 ReturnTypestateAttr::ConsumedState ReturnState;
1252
1253 if (AL.isArgIdent(0)) {
1254 IdentifierLoc *IL = AL.getArgAsIdent(0);
1255 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1256 ReturnState)) {
1257 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1258 << IL->Ident;
1259 return;
1260 }
1261 } else {
1262 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1263 << AL << AANT_ArgumentIdentifier;
1264 return;
1265 }
1266
1267 // FIXME: This check is currently being done in the analysis. It can be
1268 // enabled here only after the parser propagates attributes at
1269 // template specialization definition, not declaration.
1270 //QualType ReturnType;
1271 //
1272 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1273 // ReturnType = Param->getType();
1274 //
1275 //} else if (const CXXConstructorDecl *Constructor =
1276 // dyn_cast<CXXConstructorDecl>(D)) {
1277 // ReturnType = Constructor->getThisType()->getPointeeType();
1278 //
1279 //} else {
1280 //
1281 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1282 //}
1283 //
1284 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1285 //
1286 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1287 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1288 // ReturnType.getAsString();
1289 // return;
1290 //}
1291
1292 D->addAttr(::new (S.Context)
1293 ReturnTypestateAttr(AL.getRange(), S.Context, ReturnState,
1294 AL.getAttributeSpellingListIndex()));
1295 }
1296
handleSetTypestateAttr(Sema & S,Decl * D,const ParsedAttr & AL)1297 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1298 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1299 return;
1300
1301 SetTypestateAttr::ConsumedState NewState;
1302 if (AL.isArgIdent(0)) {
1303 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1304 StringRef Param = Ident->Ident->getName();
1305 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1306 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1307 << Param;
1308 return;
1309 }
1310 } else {
1311 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1312 << AL << AANT_ArgumentIdentifier;
1313 return;
1314 }
1315
1316 D->addAttr(::new (S.Context)
1317 SetTypestateAttr(AL.getRange(), S.Context, NewState,
1318 AL.getAttributeSpellingListIndex()));
1319 }
1320
handleTestTypestateAttr(Sema & S,Decl * D,const ParsedAttr & AL)1321 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1322 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1323 return;
1324
1325 TestTypestateAttr::ConsumedState TestState;
1326 if (AL.isArgIdent(0)) {
1327 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1328 StringRef Param = Ident->Ident->getName();
1329 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1330 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1331 << Param;
1332 return;
1333 }
1334 } else {
1335 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1336 << AL << AANT_ArgumentIdentifier;
1337 return;
1338 }
1339
1340 D->addAttr(::new (S.Context)
1341 TestTypestateAttr(AL.getRange(), S.Context, TestState,
1342 AL.getAttributeSpellingListIndex()));
1343 }
1344
handleExtVectorTypeAttr(Sema & S,Decl * D,const ParsedAttr & AL)1345 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1346 // Remember this typedef decl, we will need it later for diagnostics.
1347 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1348 }
1349
handlePackedAttr(Sema & S,Decl * D,const ParsedAttr & AL)1350 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1351 if (auto *TD = dyn_cast<TagDecl>(D))
1352 TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context,
1353 AL.getAttributeSpellingListIndex()));
1354 else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1355 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1356 !FD->getType()->isIncompleteType() &&
1357 FD->isBitField() &&
1358 S.Context.getTypeAlign(FD->getType()) <= 8);
1359
1360 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1361 if (BitfieldByteAligned)
1362 // The PS4 target needs to maintain ABI backwards compatibility.
1363 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1364 << AL << FD->getType();
1365 else
1366 FD->addAttr(::new (S.Context) PackedAttr(
1367 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1368 } else {
1369 // Report warning about changed offset in the newer compiler versions.
1370 if (BitfieldByteAligned)
1371 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1372
1373 FD->addAttr(::new (S.Context) PackedAttr(
1374 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1375 }
1376
1377 } else
1378 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1379 }
1380
checkIBOutletCommon(Sema & S,Decl * D,const ParsedAttr & AL)1381 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1382 // The IBOutlet/IBOutletCollection attributes only apply to instance
1383 // variables or properties of Objective-C classes. The outlet must also
1384 // have an object reference type.
1385 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1386 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1387 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1388 << AL << VD->getType() << 0;
1389 return false;
1390 }
1391 }
1392 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1393 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1394 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1395 << AL << PD->getType() << 1;
1396 return false;
1397 }
1398 }
1399 else {
1400 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1401 return false;
1402 }
1403
1404 return true;
1405 }
1406
handleIBOutlet(Sema & S,Decl * D,const ParsedAttr & AL)1407 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1408 if (!checkIBOutletCommon(S, D, AL))
1409 return;
1410
1411 D->addAttr(::new (S.Context)
1412 IBOutletAttr(AL.getRange(), S.Context,
1413 AL.getAttributeSpellingListIndex()));
1414 }
1415
handleIBOutletCollection(Sema & S,Decl * D,const ParsedAttr & AL)1416 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1417
1418 // The iboutletcollection attribute can have zero or one arguments.
1419 if (AL.getNumArgs() > 1) {
1420 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1421 return;
1422 }
1423
1424 if (!checkIBOutletCommon(S, D, AL))
1425 return;
1426
1427 ParsedType PT;
1428
1429 if (AL.hasParsedType())
1430 PT = AL.getTypeArg();
1431 else {
1432 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1433 S.getScopeForContext(D->getDeclContext()->getParent()));
1434 if (!PT) {
1435 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1436 return;
1437 }
1438 }
1439
1440 TypeSourceInfo *QTLoc = nullptr;
1441 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1442 if (!QTLoc)
1443 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1444
1445 // Diagnose use of non-object type in iboutletcollection attribute.
1446 // FIXME. Gnu attribute extension ignores use of builtin types in
1447 // attributes. So, __attribute__((iboutletcollection(char))) will be
1448 // treated as __attribute__((iboutletcollection())).
1449 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1450 S.Diag(AL.getLoc(),
1451 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1452 : diag::err_iboutletcollection_type) << QT;
1453 return;
1454 }
1455
1456 D->addAttr(::new (S.Context)
1457 IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc,
1458 AL.getAttributeSpellingListIndex()));
1459 }
1460
isValidPointerAttrType(QualType T,bool RefOkay)1461 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1462 if (RefOkay) {
1463 if (T->isReferenceType())
1464 return true;
1465 } else {
1466 T = T.getNonReferenceType();
1467 }
1468
1469 // The nonnull attribute, and other similar attributes, can be applied to a
1470 // transparent union that contains a pointer type.
1471 if (const RecordType *UT = T->getAsUnionType()) {
1472 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1473 RecordDecl *UD = UT->getDecl();
1474 for (const auto *I : UD->fields()) {
1475 QualType QT = I->getType();
1476 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1477 return true;
1478 }
1479 }
1480 }
1481
1482 return T->isAnyPointerType() || T->isBlockPointerType();
1483 }
1484
attrNonNullArgCheck(Sema & S,QualType T,const ParsedAttr & AL,SourceRange AttrParmRange,SourceRange TypeRange,bool isReturnValue=false)1485 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1486 SourceRange AttrParmRange,
1487 SourceRange TypeRange,
1488 bool isReturnValue = false) {
1489 if (!S.isValidPointerAttrType(T)) {
1490 if (isReturnValue)
1491 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1492 << AL << AttrParmRange << TypeRange;
1493 else
1494 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1495 << AL << AttrParmRange << TypeRange << 0;
1496 return false;
1497 }
1498 return true;
1499 }
1500
handleNonNullAttr(Sema & S,Decl * D,const ParsedAttr & AL)1501 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1502 SmallVector<ParamIdx, 8> NonNullArgs;
1503 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1504 Expr *Ex = AL.getArgAsExpr(I);
1505 ParamIdx Idx;
1506 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1507 return;
1508
1509 // Is the function argument a pointer type?
1510 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1511 !attrNonNullArgCheck(
1512 S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1513 Ex->getSourceRange(),
1514 getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1515 continue;
1516
1517 NonNullArgs.push_back(Idx);
1518 }
1519
1520 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1521 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1522 // check if the attribute came from a macro expansion or a template
1523 // instantiation.
1524 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1525 !S.inTemplateInstantiation()) {
1526 bool AnyPointers = isFunctionOrMethodVariadic(D);
1527 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1528 I != E && !AnyPointers; ++I) {
1529 QualType T = getFunctionOrMethodParamType(D, I);
1530 if (T->isDependentType() || S.isValidPointerAttrType(T))
1531 AnyPointers = true;
1532 }
1533
1534 if (!AnyPointers)
1535 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1536 }
1537
1538 ParamIdx *Start = NonNullArgs.data();
1539 unsigned Size = NonNullArgs.size();
1540 llvm::array_pod_sort(Start, Start + Size);
1541 D->addAttr(::new (S.Context)
1542 NonNullAttr(AL.getRange(), S.Context, Start, Size,
1543 AL.getAttributeSpellingListIndex()));
1544 }
1545
handleNonNullAttrParameter(Sema & S,ParmVarDecl * D,const ParsedAttr & AL)1546 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1547 const ParsedAttr &AL) {
1548 if (AL.getNumArgs() > 0) {
1549 if (D->getFunctionType()) {
1550 handleNonNullAttr(S, D, AL);
1551 } else {
1552 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1553 << D->getSourceRange();
1554 }
1555 return;
1556 }
1557
1558 // Is the argument a pointer type?
1559 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1560 D->getSourceRange()))
1561 return;
1562
1563 D->addAttr(::new (S.Context)
1564 NonNullAttr(AL.getRange(), S.Context, nullptr, 0,
1565 AL.getAttributeSpellingListIndex()));
1566 }
1567
handleReturnsNonNullAttr(Sema & S,Decl * D,const ParsedAttr & AL)1568 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1569 QualType ResultType = getFunctionOrMethodResultType(D);
1570 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1571 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1572 /* isReturnValue */ true))
1573 return;
1574
1575 D->addAttr(::new (S.Context)
1576 ReturnsNonNullAttr(AL.getRange(), S.Context,
1577 AL.getAttributeSpellingListIndex()));
1578 }
1579
handleNoEscapeAttr(Sema & S,Decl * D,const ParsedAttr & AL)1580 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1581 if (D->isInvalidDecl())
1582 return;
1583
1584 // noescape only applies to pointer types.
1585 QualType T = cast<ParmVarDecl>(D)->getType();
1586 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1587 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1588 << AL << AL.getRange() << 0;
1589 return;
1590 }
1591
1592 D->addAttr(::new (S.Context) NoEscapeAttr(
1593 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1594 }
1595
handleAssumeAlignedAttr(Sema & S,Decl * D,const ParsedAttr & AL)1596 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1597 Expr *E = AL.getArgAsExpr(0),
1598 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1599 S.AddAssumeAlignedAttr(AL.getRange(), D, E, OE,
1600 AL.getAttributeSpellingListIndex());
1601 }
1602
handleAllocAlignAttr(Sema & S,Decl * D,const ParsedAttr & AL)1603 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1604 S.AddAllocAlignAttr(AL.getRange(), D, AL.getArgAsExpr(0),
1605 AL.getAttributeSpellingListIndex());
1606 }
1607
AddAssumeAlignedAttr(SourceRange AttrRange,Decl * D,Expr * E,Expr * OE,unsigned SpellingListIndex)1608 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1609 Expr *OE, unsigned SpellingListIndex) {
1610 QualType ResultType = getFunctionOrMethodResultType(D);
1611 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1612
1613 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1614 SourceLocation AttrLoc = AttrRange.getBegin();
1615
1616 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1617 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1618 << &TmpAttr << AttrRange << SR;
1619 return;
1620 }
1621
1622 if (!E->isValueDependent()) {
1623 llvm::APSInt I(64);
1624 if (!E->isIntegerConstantExpr(I, Context)) {
1625 if (OE)
1626 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1627 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1628 << E->getSourceRange();
1629 else
1630 Diag(AttrLoc, diag::err_attribute_argument_type)
1631 << &TmpAttr << AANT_ArgumentIntegerConstant
1632 << E->getSourceRange();
1633 return;
1634 }
1635
1636 if (!I.isPowerOf2()) {
1637 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1638 << E->getSourceRange();
1639 return;
1640 }
1641 }
1642
1643 if (OE) {
1644 if (!OE->isValueDependent()) {
1645 llvm::APSInt I(64);
1646 if (!OE->isIntegerConstantExpr(I, Context)) {
1647 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1648 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1649 << OE->getSourceRange();
1650 return;
1651 }
1652 }
1653 }
1654
1655 D->addAttr(::new (Context)
1656 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1657 }
1658
AddAllocAlignAttr(SourceRange AttrRange,Decl * D,Expr * ParamExpr,unsigned SpellingListIndex)1659 void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1660 unsigned SpellingListIndex) {
1661 QualType ResultType = getFunctionOrMethodResultType(D);
1662
1663 AllocAlignAttr TmpAttr(AttrRange, Context, ParamIdx(), SpellingListIndex);
1664 SourceLocation AttrLoc = AttrRange.getBegin();
1665
1666 if (!ResultType->isDependentType() &&
1667 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1668 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1669 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1670 return;
1671 }
1672
1673 ParamIdx Idx;
1674 const auto *FuncDecl = cast<FunctionDecl>(D);
1675 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1676 /*AttrArgNo=*/1, ParamExpr, Idx))
1677 return;
1678
1679 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1680 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1681 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1682 << &TmpAttr
1683 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1684 return;
1685 }
1686
1687 D->addAttr(::new (Context)
1688 AllocAlignAttr(AttrRange, Context, Idx, SpellingListIndex));
1689 }
1690
1691 /// Normalize the attribute, __foo__ becomes foo.
1692 /// Returns true if normalization was applied.
normalizeName(StringRef & AttrName)1693 static bool normalizeName(StringRef &AttrName) {
1694 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1695 AttrName.endswith("__")) {
1696 AttrName = AttrName.drop_front(2).drop_back(2);
1697 return true;
1698 }
1699 return false;
1700 }
1701
handleOwnershipAttr(Sema & S,Decl * D,const ParsedAttr & AL)1702 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1703 // This attribute must be applied to a function declaration. The first
1704 // argument to the attribute must be an identifier, the name of the resource,
1705 // for example: malloc. The following arguments must be argument indexes, the
1706 // arguments must be of integer type for Returns, otherwise of pointer type.
1707 // The difference between Holds and Takes is that a pointer may still be used
1708 // after being held. free() should be __attribute((ownership_takes)), whereas
1709 // a list append function may well be __attribute((ownership_holds)).
1710
1711 if (!AL.isArgIdent(0)) {
1712 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1713 << AL << 1 << AANT_ArgumentIdentifier;
1714 return;
1715 }
1716
1717 // Figure out our Kind.
1718 OwnershipAttr::OwnershipKind K =
1719 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1720 AL.getAttributeSpellingListIndex()).getOwnKind();
1721
1722 // Check arguments.
1723 switch (K) {
1724 case OwnershipAttr::Takes:
1725 case OwnershipAttr::Holds:
1726 if (AL.getNumArgs() < 2) {
1727 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1728 return;
1729 }
1730 break;
1731 case OwnershipAttr::Returns:
1732 if (AL.getNumArgs() > 2) {
1733 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1734 return;
1735 }
1736 break;
1737 }
1738
1739 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1740
1741 StringRef ModuleName = Module->getName();
1742 if (normalizeName(ModuleName)) {
1743 Module = &S.PP.getIdentifierTable().get(ModuleName);
1744 }
1745
1746 SmallVector<ParamIdx, 8> OwnershipArgs;
1747 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1748 Expr *Ex = AL.getArgAsExpr(i);
1749 ParamIdx Idx;
1750 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1751 return;
1752
1753 // Is the function argument a pointer type?
1754 QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1755 int Err = -1; // No error
1756 switch (K) {
1757 case OwnershipAttr::Takes:
1758 case OwnershipAttr::Holds:
1759 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1760 Err = 0;
1761 break;
1762 case OwnershipAttr::Returns:
1763 if (!T->isIntegerType())
1764 Err = 1;
1765 break;
1766 }
1767 if (-1 != Err) {
1768 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1769 << Ex->getSourceRange();
1770 return;
1771 }
1772
1773 // Check we don't have a conflict with another ownership attribute.
1774 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1775 // Cannot have two ownership attributes of different kinds for the same
1776 // index.
1777 if (I->getOwnKind() != K && I->args_end() !=
1778 std::find(I->args_begin(), I->args_end(), Idx)) {
1779 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1780 return;
1781 } else if (K == OwnershipAttr::Returns &&
1782 I->getOwnKind() == OwnershipAttr::Returns) {
1783 // A returns attribute conflicts with any other returns attribute using
1784 // a different index.
1785 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1786 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1787 << I->args_begin()->getSourceIndex();
1788 if (I->args_size())
1789 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1790 << Idx.getSourceIndex() << Ex->getSourceRange();
1791 return;
1792 }
1793 }
1794 }
1795 OwnershipArgs.push_back(Idx);
1796 }
1797
1798 ParamIdx *Start = OwnershipArgs.data();
1799 unsigned Size = OwnershipArgs.size();
1800 llvm::array_pod_sort(Start, Start + Size);
1801 D->addAttr(::new (S.Context)
1802 OwnershipAttr(AL.getLoc(), S.Context, Module, Start, Size,
1803 AL.getAttributeSpellingListIndex()));
1804 }
1805
handleWeakRefAttr(Sema & S,Decl * D,const ParsedAttr & AL)1806 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1807 // Check the attribute arguments.
1808 if (AL.getNumArgs() > 1) {
1809 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1810 return;
1811 }
1812
1813 // gcc rejects
1814 // class c {
1815 // static int a __attribute__((weakref ("v2")));
1816 // static int b() __attribute__((weakref ("f3")));
1817 // };
1818 // and ignores the attributes of
1819 // void f(void) {
1820 // static int a __attribute__((weakref ("v2")));
1821 // }
1822 // we reject them
1823 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1824 if (!Ctx->isFileContext()) {
1825 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1826 << cast<NamedDecl>(D);
1827 return;
1828 }
1829
1830 // The GCC manual says
1831 //
1832 // At present, a declaration to which `weakref' is attached can only
1833 // be `static'.
1834 //
1835 // It also says
1836 //
1837 // Without a TARGET,
1838 // given as an argument to `weakref' or to `alias', `weakref' is
1839 // equivalent to `weak'.
1840 //
1841 // gcc 4.4.1 will accept
1842 // int a7 __attribute__((weakref));
1843 // as
1844 // int a7 __attribute__((weak));
1845 // This looks like a bug in gcc. We reject that for now. We should revisit
1846 // it if this behaviour is actually used.
1847
1848 // GCC rejects
1849 // static ((alias ("y"), weakref)).
1850 // Should we? How to check that weakref is before or after alias?
1851
1852 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1853 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1854 // StringRef parameter it was given anyway.
1855 StringRef Str;
1856 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1857 // GCC will accept anything as the argument of weakref. Should we
1858 // check for an existing decl?
1859 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1860 AL.getAttributeSpellingListIndex()));
1861
1862 D->addAttr(::new (S.Context)
1863 WeakRefAttr(AL.getRange(), S.Context,
1864 AL.getAttributeSpellingListIndex()));
1865 }
1866
handleIFuncAttr(Sema & S,Decl * D,const ParsedAttr & AL)1867 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1868 StringRef Str;
1869 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1870 return;
1871
1872 // Aliases should be on declarations, not definitions.
1873 const auto *FD = cast<FunctionDecl>(D);
1874 if (FD->isThisDeclarationADefinition()) {
1875 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1876 return;
1877 }
1878
1879 D->addAttr(::new (S.Context) IFuncAttr(AL.getRange(), S.Context, Str,
1880 AL.getAttributeSpellingListIndex()));
1881 }
1882
handleAliasAttr(Sema & S,Decl * D,const ParsedAttr & AL)1883 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1884 StringRef Str;
1885 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1886 return;
1887
1888 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1889 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1890 return;
1891 }
1892 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1893 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1894 }
1895
1896 // Aliases should be on declarations, not definitions.
1897 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1898 if (FD->isThisDeclarationADefinition()) {
1899 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1900 return;
1901 }
1902 } else {
1903 const auto *VD = cast<VarDecl>(D);
1904 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1905 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1906 return;
1907 }
1908 }
1909
1910 // Mark target used to prevent unneeded-internal-declaration warnings.
1911 if (!S.LangOpts.CPlusPlus) {
1912 // FIXME: demangle Str for C++, as the attribute refers to the mangled
1913 // linkage name, not the pre-mangled identifier.
1914 const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1915 LookupResult LR(S, target, Sema::LookupOrdinaryName);
1916 if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
1917 for (NamedDecl *ND : LR)
1918 ND->markUsed(S.Context);
1919 }
1920
1921 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1922 AL.getAttributeSpellingListIndex()));
1923 }
1924
handleTLSModelAttr(Sema & S,Decl * D,const ParsedAttr & AL)1925 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1926 StringRef Model;
1927 SourceLocation LiteralLoc;
1928 // Check that it is a string.
1929 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1930 return;
1931
1932 // Check that the value.
1933 if (Model != "global-dynamic" && Model != "local-dynamic"
1934 && Model != "initial-exec" && Model != "local-exec") {
1935 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1936 return;
1937 }
1938
1939 D->addAttr(::new (S.Context)
1940 TLSModelAttr(AL.getRange(), S.Context, Model,
1941 AL.getAttributeSpellingListIndex()));
1942 }
1943
handleRestrictAttr(Sema & S,Decl * D,const ParsedAttr & AL)1944 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1945 QualType ResultType = getFunctionOrMethodResultType(D);
1946 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1947 D->addAttr(::new (S.Context) RestrictAttr(
1948 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1949 return;
1950 }
1951
1952 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1953 << AL << getFunctionOrMethodResultSourceRange(D);
1954 }
1955
handleCPUSpecificAttr(Sema & S,Decl * D,const ParsedAttr & AL)1956 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1957 FunctionDecl *FD = cast<FunctionDecl>(D);
1958
1959 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1960 if (MD->getParent()->isLambda()) {
1961 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1962 return;
1963 }
1964 }
1965
1966 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1967 return;
1968
1969 SmallVector<IdentifierInfo *, 8> CPUs;
1970 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1971 if (!AL.isArgIdent(ArgNo)) {
1972 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1973 << AL << AANT_ArgumentIdentifier;
1974 return;
1975 }
1976
1977 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1978 StringRef CPUName = CPUArg->Ident->getName().trim();
1979
1980 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
1981 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1982 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1983 return;
1984 }
1985
1986 const TargetInfo &Target = S.Context.getTargetInfo();
1987 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1988 return Target.CPUSpecificManglingCharacter(CPUName) ==
1989 Target.CPUSpecificManglingCharacter(Cur->getName());
1990 })) {
1991 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1992 return;
1993 }
1994 CPUs.push_back(CPUArg->Ident);
1995 }
1996
1997 FD->setIsMultiVersion(true);
1998 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
1999 D->addAttr(::new (S.Context) CPUSpecificAttr(
2000 AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
2001 AL.getAttributeSpellingListIndex()));
2002 else
2003 D->addAttr(::new (S.Context) CPUDispatchAttr(
2004 AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
2005 AL.getAttributeSpellingListIndex()));
2006 }
2007
handleCommonAttr(Sema & S,Decl * D,const ParsedAttr & AL)2008 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2009 if (S.LangOpts.CPlusPlus) {
2010 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2011 << AL << AttributeLangSupport::Cpp;
2012 return;
2013 }
2014
2015 if (CommonAttr *CA = S.mergeCommonAttr(D, AL))
2016 D->addAttr(CA);
2017 }
2018
handleNakedAttr(Sema & S,Decl * D,const ParsedAttr & AL)2019 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2020 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
2021 return;
2022
2023 if (AL.isDeclspecAttribute()) {
2024 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2025 const auto &Arch = Triple.getArch();
2026 if (Arch != llvm::Triple::x86 &&
2027 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2028 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2029 << AL << Triple.getArchName();
2030 return;
2031 }
2032 }
2033
2034 D->addAttr(::new (S.Context) NakedAttr(AL.getRange(), S.Context,
2035 AL.getAttributeSpellingListIndex()));
2036 }
2037
handleNoReturnAttr(Sema & S,Decl * D,const ParsedAttr & Attrs)2038 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2039 if (hasDeclarator(D)) return;
2040
2041 if (!isa<ObjCMethodDecl>(D)) {
2042 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2043 << Attrs << ExpectedFunctionOrMethod;
2044 return;
2045 }
2046
2047 D->addAttr(::new (S.Context) NoReturnAttr(
2048 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
2049 }
2050
handleNoCfCheckAttr(Sema & S,Decl * D,const ParsedAttr & Attrs)2051 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2052 if (!S.getLangOpts().CFProtectionBranch)
2053 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2054 else
2055 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2056 }
2057
CheckAttrNoArgs(const ParsedAttr & Attrs)2058 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2059 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
2060 Attrs.setInvalid();
2061 return true;
2062 }
2063
2064 return false;
2065 }
2066
CheckAttrTarget(const ParsedAttr & AL)2067 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2068 // Check whether the attribute is valid on the current target.
2069 if (!AL.existsInTarget(Context.getTargetInfo())) {
2070 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
2071 AL.setInvalid();
2072 return true;
2073 }
2074
2075 return false;
2076 }
2077
handleAnalyzerNoReturnAttr(Sema & S,Decl * D,const ParsedAttr & AL)2078 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2079
2080 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2081 // because 'analyzer_noreturn' does not impact the type.
2082 if (!isFunctionOrMethodOrBlock(D)) {
2083 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2084 if (!VD || (!VD->getType()->isBlockPointerType() &&
2085 !VD->getType()->isFunctionPointerType())) {
2086 S.Diag(AL.getLoc(), AL.isCXX11Attribute()
2087 ? diag::err_attribute_wrong_decl_type
2088 : diag::warn_attribute_wrong_decl_type)
2089 << AL << ExpectedFunctionMethodOrBlock;
2090 return;
2091 }
2092 }
2093
2094 D->addAttr(::new (S.Context)
2095 AnalyzerNoReturnAttr(AL.getRange(), S.Context,
2096 AL.getAttributeSpellingListIndex()));
2097 }
2098
2099 // PS3 PPU-specific.
handleVecReturnAttr(Sema & S,Decl * D,const ParsedAttr & AL)2100 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2101 /*
2102 Returning a Vector Class in Registers
2103
2104 According to the PPU ABI specifications, a class with a single member of
2105 vector type is returned in memory when used as the return value of a
2106 function.
2107 This results in inefficient code when implementing vector classes. To return
2108 the value in a single vector register, add the vecreturn attribute to the
2109 class definition. This attribute is also applicable to struct types.
2110
2111 Example:
2112
2113 struct Vector
2114 {
2115 __vector float xyzw;
2116 } __attribute__((vecreturn));
2117
2118 Vector Add(Vector lhs, Vector rhs)
2119 {
2120 Vector result;
2121 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2122 return result; // This will be returned in a register
2123 }
2124 */
2125 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2126 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2127 return;
2128 }
2129
2130 const auto *R = cast<RecordDecl>(D);
2131 int count = 0;
2132
2133 if (!isa<CXXRecordDecl>(R)) {
2134 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2135 return;
2136 }
2137
2138 if (!cast<CXXRecordDecl>(R)->isPOD()) {
2139 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2140 return;
2141 }
2142
2143 for (const auto *I : R->fields()) {
2144 if ((count == 1) || !I->getType()->isVectorType()) {
2145 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2146 return;
2147 }
2148 count++;
2149 }
2150
2151 D->addAttr(::new (S.Context) VecReturnAttr(
2152 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
2153 }
2154
handleDependencyAttr(Sema & S,Scope * Scope,Decl * D,const ParsedAttr & AL)2155 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2156 const ParsedAttr &AL) {
2157 if (isa<ParmVarDecl>(D)) {
2158 // [[carries_dependency]] can only be applied to a parameter if it is a
2159 // parameter of a function declaration or lambda.
2160 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2161 S.Diag(AL.getLoc(),
2162 diag::err_carries_dependency_param_not_function_decl);
2163 return;
2164 }
2165 }
2166
2167 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2168 AL.getRange(), S.Context,
2169 AL.getAttributeSpellingListIndex()));
2170 }
2171
handleUnusedAttr(Sema & S,Decl * D,const ParsedAttr & AL)2172 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2173 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2174
2175 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2176 // about using it as an extension.
2177 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2178 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2179
2180 D->addAttr(::new (S.Context) UnusedAttr(
2181 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
2182 }
2183
handleConstructorAttr(Sema & S,Decl * D,const ParsedAttr & AL)2184 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2185 uint32_t priority = ConstructorAttr::DefaultPriority;
2186 if (AL.getNumArgs() &&
2187 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2188 return;
2189
2190 D->addAttr(::new (S.Context)
2191 ConstructorAttr(AL.getRange(), S.Context, priority,
2192 AL.getAttributeSpellingListIndex()));
2193 }
2194
handleDestructorAttr(Sema & S,Decl * D,const ParsedAttr & AL)2195 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2196 uint32_t priority = DestructorAttr::DefaultPriority;
2197 if (AL.getNumArgs() &&
2198 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2199 return;
2200
2201 D->addAttr(::new (S.Context)
2202 DestructorAttr(AL.getRange(), S.Context, priority,
2203 AL.getAttributeSpellingListIndex()));
2204 }
2205
2206 template <typename AttrTy>
handleAttrWithMessage(Sema & S,Decl * D,const ParsedAttr & AL)2207 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2208 // Handle the case where the attribute has a text message.
2209 StringRef Str;
2210 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2211 return;
2212
2213 D->addAttr(::new (S.Context) AttrTy(AL.getRange(), S.Context, Str,
2214 AL.getAttributeSpellingListIndex()));
2215 }
2216
handleObjCSuppresProtocolAttr(Sema & S,Decl * D,const ParsedAttr & AL)2217 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2218 const ParsedAttr &AL) {
2219 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2220 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2221 << AL << AL.getRange();
2222 return;
2223 }
2224
2225 D->addAttr(::new (S.Context)
2226 ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context,
2227 AL.getAttributeSpellingListIndex()));
2228 }
2229
checkAvailabilityAttr(Sema & S,SourceRange Range,IdentifierInfo * Platform,VersionTuple Introduced,VersionTuple Deprecated,VersionTuple Obsoleted)2230 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2231 IdentifierInfo *Platform,
2232 VersionTuple Introduced,
2233 VersionTuple Deprecated,
2234 VersionTuple Obsoleted) {
2235 StringRef PlatformName
2236 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2237 if (PlatformName.empty())
2238 PlatformName = Platform->getName();
2239
2240 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2241 // of these steps are needed).
2242 if (!Introduced.empty() && !Deprecated.empty() &&
2243 !(Introduced <= Deprecated)) {
2244 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2245 << 1 << PlatformName << Deprecated.getAsString()
2246 << 0 << Introduced.getAsString();
2247 return true;
2248 }
2249
2250 if (!Introduced.empty() && !Obsoleted.empty() &&
2251 !(Introduced <= Obsoleted)) {
2252 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2253 << 2 << PlatformName << Obsoleted.getAsString()
2254 << 0 << Introduced.getAsString();
2255 return true;
2256 }
2257
2258 if (!Deprecated.empty() && !Obsoleted.empty() &&
2259 !(Deprecated <= Obsoleted)) {
2260 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2261 << 2 << PlatformName << Obsoleted.getAsString()
2262 << 1 << Deprecated.getAsString();
2263 return true;
2264 }
2265
2266 return false;
2267 }
2268
2269 /// Check whether the two versions match.
2270 ///
2271 /// If either version tuple is empty, then they are assumed to match. If
2272 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
versionsMatch(const VersionTuple & X,const VersionTuple & Y,bool BeforeIsOkay)2273 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2274 bool BeforeIsOkay) {
2275 if (X.empty() || Y.empty())
2276 return true;
2277
2278 if (X == Y)
2279 return true;
2280
2281 if (BeforeIsOkay && X < Y)
2282 return true;
2283
2284 return false;
2285 }
2286
mergeAvailabilityAttr(NamedDecl * D,SourceRange Range,IdentifierInfo * Platform,bool Implicit,VersionTuple Introduced,VersionTuple Deprecated,VersionTuple Obsoleted,bool IsUnavailable,StringRef Message,bool IsStrict,StringRef Replacement,AvailabilityMergeKind AMK,unsigned AttrSpellingListIndex)2287 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2288 IdentifierInfo *Platform,
2289 bool Implicit,
2290 VersionTuple Introduced,
2291 VersionTuple Deprecated,
2292 VersionTuple Obsoleted,
2293 bool IsUnavailable,
2294 StringRef Message,
2295 bool IsStrict,
2296 StringRef Replacement,
2297 AvailabilityMergeKind AMK,
2298 unsigned AttrSpellingListIndex) {
2299 VersionTuple MergedIntroduced = Introduced;
2300 VersionTuple MergedDeprecated = Deprecated;
2301 VersionTuple MergedObsoleted = Obsoleted;
2302 bool FoundAny = false;
2303 bool OverrideOrImpl = false;
2304 switch (AMK) {
2305 case AMK_None:
2306 case AMK_Redeclaration:
2307 OverrideOrImpl = false;
2308 break;
2309
2310 case AMK_Override:
2311 case AMK_ProtocolImplementation:
2312 OverrideOrImpl = true;
2313 break;
2314 }
2315
2316 if (D->hasAttrs()) {
2317 AttrVec &Attrs = D->getAttrs();
2318 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2319 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2320 if (!OldAA) {
2321 ++i;
2322 continue;
2323 }
2324
2325 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2326 if (OldPlatform != Platform) {
2327 ++i;
2328 continue;
2329 }
2330
2331 // If there is an existing availability attribute for this platform that
2332 // is explicit and the new one is implicit use the explicit one and
2333 // discard the new implicit attribute.
2334 if (!OldAA->isImplicit() && Implicit) {
2335 return nullptr;
2336 }
2337
2338 // If there is an existing attribute for this platform that is implicit
2339 // and the new attribute is explicit then erase the old one and
2340 // continue processing the attributes.
2341 if (!Implicit && OldAA->isImplicit()) {
2342 Attrs.erase(Attrs.begin() + i);
2343 --e;
2344 continue;
2345 }
2346
2347 FoundAny = true;
2348 VersionTuple OldIntroduced = OldAA->getIntroduced();
2349 VersionTuple OldDeprecated = OldAA->getDeprecated();
2350 VersionTuple OldObsoleted = OldAA->getObsoleted();
2351 bool OldIsUnavailable = OldAA->getUnavailable();
2352
2353 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2354 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2355 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2356 !(OldIsUnavailable == IsUnavailable ||
2357 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2358 if (OverrideOrImpl) {
2359 int Which = -1;
2360 VersionTuple FirstVersion;
2361 VersionTuple SecondVersion;
2362 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2363 Which = 0;
2364 FirstVersion = OldIntroduced;
2365 SecondVersion = Introduced;
2366 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2367 Which = 1;
2368 FirstVersion = Deprecated;
2369 SecondVersion = OldDeprecated;
2370 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2371 Which = 2;
2372 FirstVersion = Obsoleted;
2373 SecondVersion = OldObsoleted;
2374 }
2375
2376 if (Which == -1) {
2377 Diag(OldAA->getLocation(),
2378 diag::warn_mismatched_availability_override_unavail)
2379 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2380 << (AMK == AMK_Override);
2381 } else {
2382 Diag(OldAA->getLocation(),
2383 diag::warn_mismatched_availability_override)
2384 << Which
2385 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2386 << FirstVersion.getAsString() << SecondVersion.getAsString()
2387 << (AMK == AMK_Override);
2388 }
2389 if (AMK == AMK_Override)
2390 Diag(Range.getBegin(), diag::note_overridden_method);
2391 else
2392 Diag(Range.getBegin(), diag::note_protocol_method);
2393 } else {
2394 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2395 Diag(Range.getBegin(), diag::note_previous_attribute);
2396 }
2397
2398 Attrs.erase(Attrs.begin() + i);
2399 --e;
2400 continue;
2401 }
2402
2403 VersionTuple MergedIntroduced2 = MergedIntroduced;
2404 VersionTuple MergedDeprecated2 = MergedDeprecated;
2405 VersionTuple MergedObsoleted2 = MergedObsoleted;
2406
2407 if (MergedIntroduced2.empty())
2408 MergedIntroduced2 = OldIntroduced;
2409 if (MergedDeprecated2.empty())
2410 MergedDeprecated2 = OldDeprecated;
2411 if (MergedObsoleted2.empty())
2412 MergedObsoleted2 = OldObsoleted;
2413
2414 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2415 MergedIntroduced2, MergedDeprecated2,
2416 MergedObsoleted2)) {
2417 Attrs.erase(Attrs.begin() + i);
2418 --e;
2419 continue;
2420 }
2421
2422 MergedIntroduced = MergedIntroduced2;
2423 MergedDeprecated = MergedDeprecated2;
2424 MergedObsoleted = MergedObsoleted2;
2425 ++i;
2426 }
2427 }
2428
2429 if (FoundAny &&
2430 MergedIntroduced == Introduced &&
2431 MergedDeprecated == Deprecated &&
2432 MergedObsoleted == Obsoleted)
2433 return nullptr;
2434
2435 // Only create a new attribute if !OverrideOrImpl, but we want to do
2436 // the checking.
2437 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2438 MergedDeprecated, MergedObsoleted) &&
2439 !OverrideOrImpl) {
2440 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2441 Introduced, Deprecated,
2442 Obsoleted, IsUnavailable, Message,
2443 IsStrict, Replacement,
2444 AttrSpellingListIndex);
2445 Avail->setImplicit(Implicit);
2446 return Avail;
2447 }
2448 return nullptr;
2449 }
2450
handleAvailabilityAttr(Sema & S,Decl * D,const ParsedAttr & AL)2451 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2452 if (!checkAttributeNumArgs(S, AL, 1))
2453 return;
2454 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2455 unsigned Index = AL.getAttributeSpellingListIndex();
2456
2457 IdentifierInfo *II = Platform->Ident;
2458 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2459 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2460 << Platform->Ident;
2461
2462 auto *ND = dyn_cast<NamedDecl>(D);
2463 if (!ND) // We warned about this already, so just return.
2464 return;
2465
2466 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2467 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2468 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2469 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2470 bool IsStrict = AL.getStrictLoc().isValid();
2471 StringRef Str;
2472 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2473 Str = SE->getString();
2474 StringRef Replacement;
2475 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2476 Replacement = SE->getString();
2477
2478 if (II->isStr("swift")) {
2479 if (Introduced.isValid() || Obsoleted.isValid() ||
2480 (!IsUnavailable && !Deprecated.isValid())) {
2481 S.Diag(AL.getLoc(),
2482 diag::warn_availability_swift_unavailable_deprecated_only);
2483 return;
2484 }
2485 }
2486
2487 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, AL.getRange(), II,
2488 false/*Implicit*/,
2489 Introduced.Version,
2490 Deprecated.Version,
2491 Obsoleted.Version,
2492 IsUnavailable, Str,
2493 IsStrict, Replacement,
2494 Sema::AMK_None,
2495 Index);
2496 if (NewAttr)
2497 D->addAttr(NewAttr);
2498
2499 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2500 // matches before the start of the watchOS platform.
2501 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2502 IdentifierInfo *NewII = nullptr;
2503 if (II->getName() == "ios")
2504 NewII = &S.Context.Idents.get("watchos");
2505 else if (II->getName() == "ios_app_extension")
2506 NewII = &S.Context.Idents.get("watchos_app_extension");
2507
2508 if (NewII) {
2509 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2510 if (Version.empty())
2511 return Version;
2512 auto Major = Version.getMajor();
2513 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2514 if (NewMajor >= 2) {
2515 if (Version.getMinor().hasValue()) {
2516 if (Version.getSubminor().hasValue())
2517 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2518 Version.getSubminor().getValue());
2519 else
2520 return VersionTuple(NewMajor, Version.getMinor().getValue());
2521 }
2522 }
2523
2524 return VersionTuple(2, 0);
2525 };
2526
2527 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2528 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2529 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2530
2531 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2532 AL.getRange(),
2533 NewII,
2534 true/*Implicit*/,
2535 NewIntroduced,
2536 NewDeprecated,
2537 NewObsoleted,
2538 IsUnavailable, Str,
2539 IsStrict,
2540 Replacement,
2541 Sema::AMK_None,
2542 Index);
2543 if (NewAttr)
2544 D->addAttr(NewAttr);
2545 }
2546 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2547 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2548 // matches before the start of the tvOS platform.
2549 IdentifierInfo *NewII = nullptr;
2550 if (II->getName() == "ios")
2551 NewII = &S.Context.Idents.get("tvos");
2552 else if (II->getName() == "ios_app_extension")
2553 NewII = &S.Context.Idents.get("tvos_app_extension");
2554
2555 if (NewII) {
2556 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2557 AL.getRange(),
2558 NewII,
2559 true/*Implicit*/,
2560 Introduced.Version,
2561 Deprecated.Version,
2562 Obsoleted.Version,
2563 IsUnavailable, Str,
2564 IsStrict,
2565 Replacement,
2566 Sema::AMK_None,
2567 Index);
2568 if (NewAttr)
2569 D->addAttr(NewAttr);
2570 }
2571 }
2572 }
2573
handleExternalSourceSymbolAttr(Sema & S,Decl * D,const ParsedAttr & AL)2574 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2575 const ParsedAttr &AL) {
2576 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2577 return;
2578 assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
2579 "Invalid number of arguments in an external_source_symbol attribute");
2580
2581 StringRef Language;
2582 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2583 Language = SE->getString();
2584 StringRef DefinedIn;
2585 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2586 DefinedIn = SE->getString();
2587 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2588
2589 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2590 AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2591 AL.getAttributeSpellingListIndex()));
2592 }
2593
2594 template <class T>
mergeVisibilityAttr(Sema & S,Decl * D,SourceRange range,typename T::VisibilityType value,unsigned attrSpellingListIndex)2595 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2596 typename T::VisibilityType value,
2597 unsigned attrSpellingListIndex) {
2598 T *existingAttr = D->getAttr<T>();
2599 if (existingAttr) {
2600 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2601 if (existingValue == value)
2602 return nullptr;
2603 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2604 S.Diag(range.getBegin(), diag::note_previous_attribute);
2605 D->dropAttr<T>();
2606 }
2607 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2608 }
2609
mergeVisibilityAttr(Decl * D,SourceRange Range,VisibilityAttr::VisibilityType Vis,unsigned AttrSpellingListIndex)2610 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2611 VisibilityAttr::VisibilityType Vis,
2612 unsigned AttrSpellingListIndex) {
2613 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2614 AttrSpellingListIndex);
2615 }
2616
mergeTypeVisibilityAttr(Decl * D,SourceRange Range,TypeVisibilityAttr::VisibilityType Vis,unsigned AttrSpellingListIndex)2617 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2618 TypeVisibilityAttr::VisibilityType Vis,
2619 unsigned AttrSpellingListIndex) {
2620 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2621 AttrSpellingListIndex);
2622 }
2623
handleVisibilityAttr(Sema & S,Decl * D,const ParsedAttr & AL,bool isTypeVisibility)2624 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2625 bool isTypeVisibility) {
2626 // Visibility attributes don't mean anything on a typedef.
2627 if (isa<TypedefNameDecl>(D)) {
2628 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2629 return;
2630 }
2631
2632 // 'type_visibility' can only go on a type or namespace.
2633 if (isTypeVisibility &&
2634 !(isa<TagDecl>(D) ||
2635 isa<ObjCInterfaceDecl>(D) ||
2636 isa<NamespaceDecl>(D))) {
2637 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2638 << AL << ExpectedTypeOrNamespace;
2639 return;
2640 }
2641
2642 // Check that the argument is a string literal.
2643 StringRef TypeStr;
2644 SourceLocation LiteralLoc;
2645 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2646 return;
2647
2648 VisibilityAttr::VisibilityType type;
2649 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2650 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2651 << TypeStr;
2652 return;
2653 }
2654
2655 // Complain about attempts to use protected visibility on targets
2656 // (like Darwin) that don't support it.
2657 if (type == VisibilityAttr::Protected &&
2658 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2659 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2660 type = VisibilityAttr::Default;
2661 }
2662
2663 unsigned Index = AL.getAttributeSpellingListIndex();
2664 Attr *newAttr;
2665 if (isTypeVisibility) {
2666 newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(),
2667 (TypeVisibilityAttr::VisibilityType) type,
2668 Index);
2669 } else {
2670 newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index);
2671 }
2672 if (newAttr)
2673 D->addAttr(newAttr);
2674 }
2675
handleObjCMethodFamilyAttr(Sema & S,Decl * D,const ParsedAttr & AL)2676 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2677 const auto *M = cast<ObjCMethodDecl>(D);
2678 if (!AL.isArgIdent(0)) {
2679 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2680 << AL << 1 << AANT_ArgumentIdentifier;
2681 return;
2682 }
2683
2684 IdentifierLoc *IL = AL.getArgAsIdent(0);
2685 ObjCMethodFamilyAttr::FamilyKind F;
2686 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2687 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2688 return;
2689 }
2690
2691 if (F == ObjCMethodFamilyAttr::OMF_init &&
2692 !M->getReturnType()->isObjCObjectPointerType()) {
2693 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2694 << M->getReturnType();
2695 // Ignore the attribute.
2696 return;
2697 }
2698
2699 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(
2700 AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex()));
2701 }
2702
handleObjCNSObject(Sema & S,Decl * D,const ParsedAttr & AL)2703 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2704 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2705 QualType T = TD->getUnderlyingType();
2706 if (!T->isCARCBridgableType()) {
2707 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2708 return;
2709 }
2710 }
2711 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2712 QualType T = PD->getType();
2713 if (!T->isCARCBridgableType()) {
2714 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2715 return;
2716 }
2717 }
2718 else {
2719 // It is okay to include this attribute on properties, e.g.:
2720 //
2721 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2722 //
2723 // In this case it follows tradition and suppresses an error in the above
2724 // case.
2725 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2726 }
2727 D->addAttr(::new (S.Context)
2728 ObjCNSObjectAttr(AL.getRange(), S.Context,
2729 AL.getAttributeSpellingListIndex()));
2730 }
2731
handleObjCIndependentClass(Sema & S,Decl * D,const ParsedAttr & AL)2732 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2733 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2734 QualType T = TD->getUnderlyingType();
2735 if (!T->isObjCObjectPointerType()) {
2736 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2737 return;
2738 }
2739 } else {
2740 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2741 return;
2742 }
2743 D->addAttr(::new (S.Context)
2744 ObjCIndependentClassAttr(AL.getRange(), S.Context,
2745 AL.getAttributeSpellingListIndex()));
2746 }
2747
handleBlocksAttr(Sema & S,Decl * D,const ParsedAttr & AL)2748 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2749 if (!AL.isArgIdent(0)) {
2750 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2751 << AL << 1 << AANT_ArgumentIdentifier;
2752 return;
2753 }
2754
2755 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2756 BlocksAttr::BlockType type;
2757 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2758 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2759 return;
2760 }
2761
2762 D->addAttr(::new (S.Context)
2763 BlocksAttr(AL.getRange(), S.Context, type,
2764 AL.getAttributeSpellingListIndex()));
2765 }
2766
handleSentinelAttr(Sema & S,Decl * D,const ParsedAttr & AL)2767 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2768 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2769 if (AL.getNumArgs() > 0) {
2770 Expr *E = AL.getArgAsExpr(0);
2771 llvm::APSInt Idx(32);
2772 if (E->isTypeDependent() || E->isValueDependent() ||
2773 !E->isIntegerConstantExpr(Idx, S.Context)) {
2774 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2775 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2776 return;
2777 }
2778
2779 if (Idx.isSigned() && Idx.isNegative()) {
2780 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2781 << E->getSourceRange();
2782 return;
2783 }
2784
2785 sentinel = Idx.getZExtValue();
2786 }
2787
2788 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2789 if (AL.getNumArgs() > 1) {
2790 Expr *E = AL.getArgAsExpr(1);
2791 llvm::APSInt Idx(32);
2792 if (E->isTypeDependent() || E->isValueDependent() ||
2793 !E->isIntegerConstantExpr(Idx, S.Context)) {
2794 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2795 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2796 return;
2797 }
2798 nullPos = Idx.getZExtValue();
2799
2800 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2801 // FIXME: This error message could be improved, it would be nice
2802 // to say what the bounds actually are.
2803 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2804 << E->getSourceRange();
2805 return;
2806 }
2807 }
2808
2809 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2810 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2811 if (isa<FunctionNoProtoType>(FT)) {
2812 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2813 return;
2814 }
2815
2816 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2817 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2818 return;
2819 }
2820 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2821 if (!MD->isVariadic()) {
2822 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2823 return;
2824 }
2825 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2826 if (!BD->isVariadic()) {
2827 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2828 return;
2829 }
2830 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2831 QualType Ty = V->getType();
2832 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2833 const FunctionType *FT = Ty->isFunctionPointerType()
2834 ? D->getFunctionType()
2835 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2836 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2837 int m = Ty->isFunctionPointerType() ? 0 : 1;
2838 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2839 return;
2840 }
2841 } else {
2842 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2843 << AL << ExpectedFunctionMethodOrBlock;
2844 return;
2845 }
2846 } else {
2847 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2848 << AL << ExpectedFunctionMethodOrBlock;
2849 return;
2850 }
2851 D->addAttr(::new (S.Context)
2852 SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos,
2853 AL.getAttributeSpellingListIndex()));
2854 }
2855
handleWarnUnusedResult(Sema & S,Decl * D,const ParsedAttr & AL)2856 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2857 if (D->getFunctionType() &&
2858 D->getFunctionType()->getReturnType()->isVoidType()) {
2859 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2860 return;
2861 }
2862 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2863 if (MD->getReturnType()->isVoidType()) {
2864 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2865 return;
2866 }
2867
2868 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2869 // about using it as an extension.
2870 if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() &&
2871 !AL.getScopeName())
2872 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2873
2874 D->addAttr(::new (S.Context)
2875 WarnUnusedResultAttr(AL.getRange(), S.Context,
2876 AL.getAttributeSpellingListIndex()));
2877 }
2878
handleWeakImportAttr(Sema & S,Decl * D,const ParsedAttr & AL)2879 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2880 // weak_import only applies to variable & function declarations.
2881 bool isDef = false;
2882 if (!D->canBeWeakImported(isDef)) {
2883 if (isDef)
2884 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2885 << "weak_import";
2886 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2887 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2888 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2889 // Nothing to warn about here.
2890 } else
2891 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2892 << AL << ExpectedVariableOrFunction;
2893
2894 return;
2895 }
2896
2897 D->addAttr(::new (S.Context)
2898 WeakImportAttr(AL.getRange(), S.Context,
2899 AL.getAttributeSpellingListIndex()));
2900 }
2901
2902 // Handles reqd_work_group_size and work_group_size_hint.
2903 template <typename WorkGroupAttr>
handleWorkGroupSize(Sema & S,Decl * D,const ParsedAttr & AL)2904 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2905 uint32_t WGSize[3];
2906 for (unsigned i = 0; i < 3; ++i) {
2907 const Expr *E = AL.getArgAsExpr(i);
2908 if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2909 /*StrictlyUnsigned=*/true))
2910 return;
2911 if (WGSize[i] == 0) {
2912 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2913 << AL << E->getSourceRange();
2914 return;
2915 }
2916 }
2917
2918 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2919 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2920 Existing->getYDim() == WGSize[1] &&
2921 Existing->getZDim() == WGSize[2]))
2922 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2923
2924 D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context,
2925 WGSize[0], WGSize[1], WGSize[2],
2926 AL.getAttributeSpellingListIndex()));
2927 }
2928
2929 // Handles intel_reqd_sub_group_size.
handleSubGroupSize(Sema & S,Decl * D,const ParsedAttr & AL)2930 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2931 uint32_t SGSize;
2932 const Expr *E = AL.getArgAsExpr(0);
2933 if (!checkUInt32Argument(S, AL, E, SGSize))
2934 return;
2935 if (SGSize == 0) {
2936 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2937 << AL << E->getSourceRange();
2938 return;
2939 }
2940
2941 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2942 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2943 if (Existing && Existing->getSubGroupSize() != SGSize)
2944 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2945
2946 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2947 AL.getRange(), S.Context, SGSize,
2948 AL.getAttributeSpellingListIndex()));
2949 }
2950
handleVecTypeHint(Sema & S,Decl * D,const ParsedAttr & AL)2951 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2952 if (!AL.hasParsedType()) {
2953 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2954 return;
2955 }
2956
2957 TypeSourceInfo *ParmTSI = nullptr;
2958 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2959 assert(ParmTSI && "no type source info for attribute argument");
2960
2961 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2962 (ParmType->isBooleanType() ||
2963 !ParmType->isIntegralType(S.getASTContext()))) {
2964 S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint)
2965 << ParmType;
2966 return;
2967 }
2968
2969 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2970 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2971 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2972 return;
2973 }
2974 }
2975
2976 D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context,
2977 ParmTSI,
2978 AL.getAttributeSpellingListIndex()));
2979 }
2980
mergeSectionAttr(Decl * D,SourceRange Range,StringRef Name,unsigned AttrSpellingListIndex)2981 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2982 StringRef Name,
2983 unsigned AttrSpellingListIndex) {
2984 // Explicit or partial specializations do not inherit
2985 // the section attribute from the primary template.
2986 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2987 if (AttrSpellingListIndex == SectionAttr::Declspec_allocate &&
2988 FD->isFunctionTemplateSpecialization())
2989 return nullptr;
2990 }
2991 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2992 if (ExistingAttr->getName() == Name)
2993 return nullptr;
2994 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2995 << 1 /*section*/;
2996 Diag(Range.getBegin(), diag::note_previous_attribute);
2997 return nullptr;
2998 }
2999 return ::new (Context) SectionAttr(Range, Context, Name,
3000 AttrSpellingListIndex);
3001 }
3002
checkSectionName(SourceLocation LiteralLoc,StringRef SecName)3003 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3004 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
3005 if (!Error.empty()) {
3006 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
3007 << 1 /*'section'*/;
3008 return false;
3009 }
3010 return true;
3011 }
3012
handleSectionAttr(Sema & S,Decl * D,const ParsedAttr & AL)3013 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3014 // Make sure that there is a string literal as the sections's single
3015 // argument.
3016 StringRef Str;
3017 SourceLocation LiteralLoc;
3018 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3019 return;
3020
3021 if (!S.checkSectionName(LiteralLoc, Str))
3022 return;
3023
3024 // If the target wants to validate the section specifier, make it happen.
3025 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
3026 if (!Error.empty()) {
3027 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3028 << Error;
3029 return;
3030 }
3031
3032 unsigned Index = AL.getAttributeSpellingListIndex();
3033 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index);
3034 if (NewAttr)
3035 D->addAttr(NewAttr);
3036 }
3037
checkCodeSegName(Sema & S,SourceLocation LiteralLoc,StringRef CodeSegName)3038 static bool checkCodeSegName(Sema&S, SourceLocation LiteralLoc, StringRef CodeSegName) {
3039 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
3040 if (!Error.empty()) {
3041 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
3042 << 0 /*'code-seg'*/;
3043 return false;
3044 }
3045 return true;
3046 }
3047
mergeCodeSegAttr(Decl * D,SourceRange Range,StringRef Name,unsigned AttrSpellingListIndex)3048 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range,
3049 StringRef Name,
3050 unsigned AttrSpellingListIndex) {
3051 // Explicit or partial specializations do not inherit
3052 // the code_seg attribute from the primary template.
3053 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3054 if (FD->isFunctionTemplateSpecialization())
3055 return nullptr;
3056 }
3057 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3058 if (ExistingAttr->getName() == Name)
3059 return nullptr;
3060 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3061 << 0 /*codeseg*/;
3062 Diag(Range.getBegin(), diag::note_previous_attribute);
3063 return nullptr;
3064 }
3065 return ::new (Context) CodeSegAttr(Range, Context, Name,
3066 AttrSpellingListIndex);
3067 }
3068
handleCodeSegAttr(Sema & S,Decl * D,const ParsedAttr & AL)3069 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3070 StringRef Str;
3071 SourceLocation LiteralLoc;
3072 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3073 return;
3074 if (!checkCodeSegName(S, LiteralLoc, Str))
3075 return;
3076 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3077 if (!ExistingAttr->isImplicit()) {
3078 S.Diag(AL.getLoc(),
3079 ExistingAttr->getName() == Str
3080 ? diag::warn_duplicate_codeseg_attribute
3081 : diag::err_conflicting_codeseg_attribute);
3082 return;
3083 }
3084 D->dropAttr<CodeSegAttr>();
3085 }
3086 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL.getRange(), Str,
3087 AL.getAttributeSpellingListIndex()))
3088 D->addAttr(CSA);
3089 }
3090
3091 // Check for things we'd like to warn about. Multiversioning issues are
3092 // handled later in the process, once we know how many exist.
checkTargetAttr(SourceLocation LiteralLoc,StringRef AttrStr)3093 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3094 enum FirstParam { Unsupported, Duplicate };
3095 enum SecondParam { None, Architecture };
3096 for (auto Str : {"tune=", "fpmath="})
3097 if (AttrStr.find(Str) != StringRef::npos)
3098 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3099 << Unsupported << None << Str;
3100
3101 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3102
3103 if (!ParsedAttrs.Architecture.empty() &&
3104 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3105 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3106 << Unsupported << Architecture << ParsedAttrs.Architecture;
3107
3108 if (ParsedAttrs.DuplicateArchitecture)
3109 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3110 << Duplicate << None << "arch=";
3111
3112 for (const auto &Feature : ParsedAttrs.Features) {
3113 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3114 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3115 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3116 << Unsupported << None << CurFeature;
3117 }
3118
3119 return false;
3120 }
3121
handleTargetAttr(Sema & S,Decl * D,const ParsedAttr & AL)3122 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3123 StringRef Str;
3124 SourceLocation LiteralLoc;
3125 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3126 S.checkTargetAttr(LiteralLoc, Str))
3127 return;
3128
3129 unsigned Index = AL.getAttributeSpellingListIndex();
3130 TargetAttr *NewAttr =
3131 ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index);
3132 D->addAttr(NewAttr);
3133 }
3134
handleMinVectorWidthAttr(Sema & S,Decl * D,const ParsedAttr & AL)3135 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3136 Expr *E = AL.getArgAsExpr(0);
3137 uint32_t VecWidth;
3138 if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3139 AL.setInvalid();
3140 return;
3141 }
3142
3143 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3144 if (Existing && Existing->getVectorWidth() != VecWidth) {
3145 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3146 return;
3147 }
3148
3149 D->addAttr(::new (S.Context)
3150 MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth,
3151 AL.getAttributeSpellingListIndex()));
3152 }
3153
handleCleanupAttr(Sema & S,Decl * D,const ParsedAttr & AL)3154 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3155 Expr *E = AL.getArgAsExpr(0);
3156 SourceLocation Loc = E->getExprLoc();
3157 FunctionDecl *FD = nullptr;
3158 DeclarationNameInfo NI;
3159
3160 // gcc only allows for simple identifiers. Since we support more than gcc, we
3161 // will warn the user.
3162 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3163 if (DRE->hasQualifier())
3164 S.Diag(Loc, diag::warn_cleanup_ext);
3165 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3166 NI = DRE->getNameInfo();
3167 if (!FD) {
3168 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3169 << NI.getName();
3170 return;
3171 }
3172 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3173 if (ULE->hasExplicitTemplateArgs())
3174 S.Diag(Loc, diag::warn_cleanup_ext);
3175 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3176 NI = ULE->getNameInfo();
3177 if (!FD) {
3178 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3179 << NI.getName();
3180 if (ULE->getType() == S.Context.OverloadTy)
3181 S.NoteAllOverloadCandidates(ULE);
3182 return;
3183 }
3184 } else {
3185 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3186 return;
3187 }
3188
3189 if (FD->getNumParams() != 1) {
3190 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3191 << NI.getName();
3192 return;
3193 }
3194
3195 // We're currently more strict than GCC about what function types we accept.
3196 // If this ever proves to be a problem it should be easy to fix.
3197 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3198 QualType ParamTy = FD->getParamDecl(0)->getType();
3199 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3200 ParamTy, Ty) != Sema::Compatible) {
3201 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3202 << NI.getName() << ParamTy << Ty;
3203 return;
3204 }
3205
3206 D->addAttr(::new (S.Context)
3207 CleanupAttr(AL.getRange(), S.Context, FD,
3208 AL.getAttributeSpellingListIndex()));
3209 }
3210
handleEnumExtensibilityAttr(Sema & S,Decl * D,const ParsedAttr & AL)3211 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3212 const ParsedAttr &AL) {
3213 if (!AL.isArgIdent(0)) {
3214 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3215 << AL << 0 << AANT_ArgumentIdentifier;
3216 return;
3217 }
3218
3219 EnumExtensibilityAttr::Kind ExtensibilityKind;
3220 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3221 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3222 ExtensibilityKind)) {
3223 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3224 return;
3225 }
3226
3227 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3228 AL.getRange(), S.Context, ExtensibilityKind,
3229 AL.getAttributeSpellingListIndex()));
3230 }
3231
3232 /// Handle __attribute__((format_arg((idx)))) attribute based on
3233 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
handleFormatArgAttr(Sema & S,Decl * D,const ParsedAttr & AL)3234 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3235 Expr *IdxExpr = AL.getArgAsExpr(0);
3236 ParamIdx Idx;
3237 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3238 return;
3239
3240 // Make sure the format string is really a string.
3241 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3242
3243 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3244 if (NotNSStringTy &&
3245 !isCFStringType(Ty, S.Context) &&
3246 (!Ty->isPointerType() ||
3247 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3248 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3249 << "a string type" << IdxExpr->getSourceRange()
3250 << getFunctionOrMethodParamRange(D, 0);
3251 return;
3252 }
3253 Ty = getFunctionOrMethodResultType(D);
3254 if (!isNSStringType(Ty, S.Context) &&
3255 !isCFStringType(Ty, S.Context) &&
3256 (!Ty->isPointerType() ||
3257 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3258 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3259 << (NotNSStringTy ? "string type" : "NSString")
3260 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3261 return;
3262 }
3263
3264 D->addAttr(::new (S.Context) FormatArgAttr(
3265 AL.getRange(), S.Context, Idx, AL.getAttributeSpellingListIndex()));
3266 }
3267
3268 enum FormatAttrKind {
3269 CFStringFormat,
3270 NSStringFormat,
3271 StrftimeFormat,
3272 SupportedFormat,
3273 IgnoredFormat,
3274 InvalidFormat
3275 };
3276
3277 /// getFormatAttrKind - Map from format attribute names to supported format
3278 /// types.
getFormatAttrKind(StringRef Format)3279 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3280 return llvm::StringSwitch<FormatAttrKind>(Format)
3281 // Check for formats that get handled specially.
3282 .Case("NSString", NSStringFormat)
3283 .Case("CFString", CFStringFormat)
3284 .Case("strftime", StrftimeFormat)
3285
3286 // Otherwise, check for supported formats.
3287 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3288 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3289 .Case("kprintf", SupportedFormat) // OpenBSD.
3290 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3291 .Case("os_trace", SupportedFormat)
3292 .Case("os_log", SupportedFormat)
3293
3294 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3295 .Default(InvalidFormat);
3296 }
3297
3298 /// Handle __attribute__((init_priority(priority))) attributes based on
3299 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
handleInitPriorityAttr(Sema & S,Decl * D,const ParsedAttr & AL)3300 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3301 if (!S.getLangOpts().CPlusPlus) {
3302 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3303 return;
3304 }
3305
3306 if (S.getCurFunctionOrMethodDecl()) {
3307 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3308 AL.setInvalid();
3309 return;
3310 }
3311 QualType T = cast<VarDecl>(D)->getType();
3312 if (S.Context.getAsArrayType(T))
3313 T = S.Context.getBaseElementType(T);
3314 if (!T->getAs<RecordType>()) {
3315 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3316 AL.setInvalid();
3317 return;
3318 }
3319
3320 Expr *E = AL.getArgAsExpr(0);
3321 uint32_t prioritynum;
3322 if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3323 AL.setInvalid();
3324 return;
3325 }
3326
3327 if (prioritynum < 101 || prioritynum > 65535) {
3328 S.Diag(AL.getLoc(), diag::err_attribute_argument_outof_range)
3329 << E->getSourceRange() << AL << 101 << 65535;
3330 AL.setInvalid();
3331 return;
3332 }
3333 D->addAttr(::new (S.Context)
3334 InitPriorityAttr(AL.getRange(), S.Context, prioritynum,
3335 AL.getAttributeSpellingListIndex()));
3336 }
3337
mergeFormatAttr(Decl * D,SourceRange Range,IdentifierInfo * Format,int FormatIdx,int FirstArg,unsigned AttrSpellingListIndex)3338 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3339 IdentifierInfo *Format, int FormatIdx,
3340 int FirstArg,
3341 unsigned AttrSpellingListIndex) {
3342 // Check whether we already have an equivalent format attribute.
3343 for (auto *F : D->specific_attrs<FormatAttr>()) {
3344 if (F->getType() == Format &&
3345 F->getFormatIdx() == FormatIdx &&
3346 F->getFirstArg() == FirstArg) {
3347 // If we don't have a valid location for this attribute, adopt the
3348 // location.
3349 if (F->getLocation().isInvalid())
3350 F->setRange(Range);
3351 return nullptr;
3352 }
3353 }
3354
3355 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3356 FirstArg, AttrSpellingListIndex);
3357 }
3358
3359 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3360 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
handleFormatAttr(Sema & S,Decl * D,const ParsedAttr & AL)3361 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3362 if (!AL.isArgIdent(0)) {
3363 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3364 << AL << 1 << AANT_ArgumentIdentifier;
3365 return;
3366 }
3367
3368 // In C++ the implicit 'this' function parameter also counts, and they are
3369 // counted from one.
3370 bool HasImplicitThisParam = isInstanceMethod(D);
3371 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3372
3373 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3374 StringRef Format = II->getName();
3375
3376 if (normalizeName(Format)) {
3377 // If we've modified the string name, we need a new identifier for it.
3378 II = &S.Context.Idents.get(Format);
3379 }
3380
3381 // Check for supported formats.
3382 FormatAttrKind Kind = getFormatAttrKind(Format);
3383
3384 if (Kind == IgnoredFormat)
3385 return;
3386
3387 if (Kind == InvalidFormat) {
3388 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3389 << AL << II->getName();
3390 return;
3391 }
3392
3393 // checks for the 2nd argument
3394 Expr *IdxExpr = AL.getArgAsExpr(1);
3395 uint32_t Idx;
3396 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3397 return;
3398
3399 if (Idx < 1 || Idx > NumArgs) {
3400 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3401 << AL << 2 << IdxExpr->getSourceRange();
3402 return;
3403 }
3404
3405 // FIXME: Do we need to bounds check?
3406 unsigned ArgIdx = Idx - 1;
3407
3408 if (HasImplicitThisParam) {
3409 if (ArgIdx == 0) {
3410 S.Diag(AL.getLoc(),
3411 diag::err_format_attribute_implicit_this_format_string)
3412 << IdxExpr->getSourceRange();
3413 return;
3414 }
3415 ArgIdx--;
3416 }
3417
3418 // make sure the format string is really a string
3419 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3420
3421 if (Kind == CFStringFormat) {
3422 if (!isCFStringType(Ty, S.Context)) {
3423 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3424 << "a CFString" << IdxExpr->getSourceRange()
3425 << getFunctionOrMethodParamRange(D, ArgIdx);
3426 return;
3427 }
3428 } else if (Kind == NSStringFormat) {
3429 // FIXME: do we need to check if the type is NSString*? What are the
3430 // semantics?
3431 if (!isNSStringType(Ty, S.Context)) {
3432 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3433 << "an NSString" << IdxExpr->getSourceRange()
3434 << getFunctionOrMethodParamRange(D, ArgIdx);
3435 return;
3436 }
3437 } else if (!Ty->isPointerType() ||
3438 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3439 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3440 << "a string type" << IdxExpr->getSourceRange()
3441 << getFunctionOrMethodParamRange(D, ArgIdx);
3442 return;
3443 }
3444
3445 // check the 3rd argument
3446 Expr *FirstArgExpr = AL.getArgAsExpr(2);
3447 uint32_t FirstArg;
3448 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3449 return;
3450
3451 // check if the function is variadic if the 3rd argument non-zero
3452 if (FirstArg != 0) {
3453 if (isFunctionOrMethodVariadic(D)) {
3454 ++NumArgs; // +1 for ...
3455 } else {
3456 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3457 return;
3458 }
3459 }
3460
3461 // strftime requires FirstArg to be 0 because it doesn't read from any
3462 // variable the input is just the current time + the format string.
3463 if (Kind == StrftimeFormat) {
3464 if (FirstArg != 0) {
3465 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3466 << FirstArgExpr->getSourceRange();
3467 return;
3468 }
3469 // if 0 it disables parameter checking (to use with e.g. va_list)
3470 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3471 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3472 << AL << 3 << FirstArgExpr->getSourceRange();
3473 return;
3474 }
3475
3476 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II,
3477 Idx, FirstArg,
3478 AL.getAttributeSpellingListIndex());
3479 if (NewAttr)
3480 D->addAttr(NewAttr);
3481 }
3482
handleTransparentUnionAttr(Sema & S,Decl * D,const ParsedAttr & AL)3483 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3484 // Try to find the underlying union declaration.
3485 RecordDecl *RD = nullptr;
3486 const auto *TD = dyn_cast<TypedefNameDecl>(D);
3487 if (TD && TD->getUnderlyingType()->isUnionType())
3488 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3489 else
3490 RD = dyn_cast<RecordDecl>(D);
3491
3492 if (!RD || !RD->isUnion()) {
3493 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3494 << ExpectedUnion;
3495 return;
3496 }
3497
3498 if (!RD->isCompleteDefinition()) {
3499 if (!RD->isBeingDefined())
3500 S.Diag(AL.getLoc(),
3501 diag::warn_transparent_union_attribute_not_definition);
3502 return;
3503 }
3504
3505 RecordDecl::field_iterator Field = RD->field_begin(),
3506 FieldEnd = RD->field_end();
3507 if (Field == FieldEnd) {
3508 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3509 return;
3510 }
3511
3512 FieldDecl *FirstField = *Field;
3513 QualType FirstType = FirstField->getType();
3514 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3515 S.Diag(FirstField->getLocation(),
3516 diag::warn_transparent_union_attribute_floating)
3517 << FirstType->isVectorType() << FirstType;
3518 return;
3519 }
3520
3521 if (FirstType->isIncompleteType())
3522 return;
3523 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3524 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3525 for (; Field != FieldEnd; ++Field) {
3526 QualType FieldType = Field->getType();
3527 if (FieldType->isIncompleteType())
3528 return;
3529 // FIXME: this isn't fully correct; we also need to test whether the
3530 // members of the union would all have the same calling convention as the
3531 // first member of the union. Checking just the size and alignment isn't
3532 // sufficient (consider structs passed on the stack instead of in registers
3533 // as an example).
3534 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3535 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3536 // Warn if we drop the attribute.
3537 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3538 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3539 : S.Context.getTypeAlign(FieldType);
3540 S.Diag(Field->getLocation(),
3541 diag::warn_transparent_union_attribute_field_size_align)
3542 << isSize << Field->getDeclName() << FieldBits;
3543 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3544 S.Diag(FirstField->getLocation(),
3545 diag::note_transparent_union_first_field_size_align)
3546 << isSize << FirstBits;
3547 return;
3548 }
3549 }
3550
3551 RD->addAttr(::new (S.Context)
3552 TransparentUnionAttr(AL.getRange(), S.Context,
3553 AL.getAttributeSpellingListIndex()));
3554 }
3555
handleAnnotateAttr(Sema & S,Decl * D,const ParsedAttr & AL)3556 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3557 // Make sure that there is a string literal as the annotation's single
3558 // argument.
3559 StringRef Str;
3560 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3561 return;
3562
3563 // Don't duplicate annotations that are already set.
3564 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3565 if (I->getAnnotation() == Str)
3566 return;
3567 }
3568
3569 D->addAttr(::new (S.Context)
3570 AnnotateAttr(AL.getRange(), S.Context, Str,
3571 AL.getAttributeSpellingListIndex()));
3572 }
3573
handleAlignValueAttr(Sema & S,Decl * D,const ParsedAttr & AL)3574 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3575 S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0),
3576 AL.getAttributeSpellingListIndex());
3577 }
3578
AddAlignValueAttr(SourceRange AttrRange,Decl * D,Expr * E,unsigned SpellingListIndex)3579 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3580 unsigned SpellingListIndex) {
3581 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3582 SourceLocation AttrLoc = AttrRange.getBegin();
3583
3584 QualType T;
3585 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3586 T = TD->getUnderlyingType();
3587 else if (const auto *VD = dyn_cast<ValueDecl>(D))
3588 T = VD->getType();
3589 else
3590 llvm_unreachable("Unknown decl type for align_value");
3591
3592 if (!T->isDependentType() && !T->isAnyPointerType() &&
3593 !T->isReferenceType() && !T->isMemberPointerType()) {
3594 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3595 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3596 return;
3597 }
3598
3599 if (!E->isValueDependent()) {
3600 llvm::APSInt Alignment;
3601 ExprResult ICE
3602 = VerifyIntegerConstantExpression(E, &Alignment,
3603 diag::err_align_value_attribute_argument_not_int,
3604 /*AllowFold*/ false);
3605 if (ICE.isInvalid())
3606 return;
3607
3608 if (!Alignment.isPowerOf2()) {
3609 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3610 << E->getSourceRange();
3611 return;
3612 }
3613
3614 D->addAttr(::new (Context)
3615 AlignValueAttr(AttrRange, Context, ICE.get(),
3616 SpellingListIndex));
3617 return;
3618 }
3619
3620 // Save dependent expressions in the AST to be instantiated.
3621 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3622 }
3623
handleAlignedAttr(Sema & S,Decl * D,const ParsedAttr & AL)3624 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3625 // check the attribute arguments.
3626 if (AL.getNumArgs() > 1) {
3627 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3628 return;
3629 }
3630
3631 if (AL.getNumArgs() == 0) {
3632 D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context,
3633 true, nullptr, AL.getAttributeSpellingListIndex()));
3634 return;
3635 }
3636
3637 Expr *E = AL.getArgAsExpr(0);
3638 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3639 S.Diag(AL.getEllipsisLoc(),
3640 diag::err_pack_expansion_without_parameter_packs);
3641 return;
3642 }
3643
3644 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3645 return;
3646
3647 S.AddAlignedAttr(AL.getRange(), D, E, AL.getAttributeSpellingListIndex(),
3648 AL.isPackExpansion());
3649 }
3650
AddAlignedAttr(SourceRange AttrRange,Decl * D,Expr * E,unsigned SpellingListIndex,bool IsPackExpansion)3651 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3652 unsigned SpellingListIndex, bool IsPackExpansion) {
3653 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3654 SourceLocation AttrLoc = AttrRange.getBegin();
3655
3656 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3657 if (TmpAttr.isAlignas()) {
3658 // C++11 [dcl.align]p1:
3659 // An alignment-specifier may be applied to a variable or to a class
3660 // data member, but it shall not be applied to a bit-field, a function
3661 // parameter, the formal parameter of a catch clause, or a variable
3662 // declared with the register storage class specifier. An
3663 // alignment-specifier may also be applied to the declaration of a class
3664 // or enumeration type.
3665 // C11 6.7.5/2:
3666 // An alignment attribute shall not be specified in a declaration of
3667 // a typedef, or a bit-field, or a function, or a parameter, or an
3668 // object declared with the register storage-class specifier.
3669 int DiagKind = -1;
3670 if (isa<ParmVarDecl>(D)) {
3671 DiagKind = 0;
3672 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3673 if (VD->getStorageClass() == SC_Register)
3674 DiagKind = 1;
3675 if (VD->isExceptionVariable())
3676 DiagKind = 2;
3677 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3678 if (FD->isBitField())
3679 DiagKind = 3;
3680 } else if (!isa<TagDecl>(D)) {
3681 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3682 << (TmpAttr.isC11() ? ExpectedVariableOrField
3683 : ExpectedVariableFieldOrTag);
3684 return;
3685 }
3686 if (DiagKind != -1) {
3687 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3688 << &TmpAttr << DiagKind;
3689 return;
3690 }
3691 }
3692
3693 if (E->isValueDependent()) {
3694 // We can't support a dependent alignment on a non-dependent type,
3695 // because we have no way to model that a type is "alignment-dependent"
3696 // but not dependent in any other way.
3697 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3698 if (!TND->getUnderlyingType()->isDependentType()) {
3699 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3700 << E->getSourceRange();
3701 return;
3702 }
3703 }
3704
3705 // Save dependent expressions in the AST to be instantiated.
3706 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3707 AA->setPackExpansion(IsPackExpansion);
3708 D->addAttr(AA);
3709 return;
3710 }
3711
3712 // FIXME: Cache the number on the AL object?
3713 llvm::APSInt Alignment;
3714 ExprResult ICE
3715 = VerifyIntegerConstantExpression(E, &Alignment,
3716 diag::err_aligned_attribute_argument_not_int,
3717 /*AllowFold*/ false);
3718 if (ICE.isInvalid())
3719 return;
3720
3721 uint64_t AlignVal = Alignment.getZExtValue();
3722
3723 // C++11 [dcl.align]p2:
3724 // -- if the constant expression evaluates to zero, the alignment
3725 // specifier shall have no effect
3726 // C11 6.7.5p6:
3727 // An alignment specification of zero has no effect.
3728 if (!(TmpAttr.isAlignas() && !Alignment)) {
3729 if (!llvm::isPowerOf2_64(AlignVal)) {
3730 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3731 << E->getSourceRange();
3732 return;
3733 }
3734 }
3735
3736 // Alignment calculations can wrap around if it's greater than 2**28.
3737 unsigned MaxValidAlignment =
3738 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3739 : 268435456;
3740 if (AlignVal > MaxValidAlignment) {
3741 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3742 << E->getSourceRange();
3743 return;
3744 }
3745
3746 if (Context.getTargetInfo().isTLSSupported()) {
3747 unsigned MaxTLSAlign =
3748 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3749 .getQuantity();
3750 const auto *VD = dyn_cast<VarDecl>(D);
3751 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3752 VD->getTLSKind() != VarDecl::TLS_None) {
3753 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3754 << (unsigned)AlignVal << VD << MaxTLSAlign;
3755 return;
3756 }
3757 }
3758
3759 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3760 ICE.get(), SpellingListIndex);
3761 AA->setPackExpansion(IsPackExpansion);
3762 D->addAttr(AA);
3763 }
3764
AddAlignedAttr(SourceRange AttrRange,Decl * D,TypeSourceInfo * TS,unsigned SpellingListIndex,bool IsPackExpansion)3765 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3766 unsigned SpellingListIndex, bool IsPackExpansion) {
3767 // FIXME: Cache the number on the AL object if non-dependent?
3768 // FIXME: Perform checking of type validity
3769 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3770 SpellingListIndex);
3771 AA->setPackExpansion(IsPackExpansion);
3772 D->addAttr(AA);
3773 }
3774
CheckAlignasUnderalignment(Decl * D)3775 void Sema::CheckAlignasUnderalignment(Decl *D) {
3776 assert(D->hasAttrs() && "no attributes on decl");
3777
3778 QualType UnderlyingTy, DiagTy;
3779 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3780 UnderlyingTy = DiagTy = VD->getType();
3781 } else {
3782 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3783 if (const auto *ED = dyn_cast<EnumDecl>(D))
3784 UnderlyingTy = ED->getIntegerType();
3785 }
3786 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3787 return;
3788
3789 // C++11 [dcl.align]p5, C11 6.7.5/4:
3790 // The combined effect of all alignment attributes in a declaration shall
3791 // not specify an alignment that is less strict than the alignment that
3792 // would otherwise be required for the entity being declared.
3793 AlignedAttr *AlignasAttr = nullptr;
3794 unsigned Align = 0;
3795 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3796 if (I->isAlignmentDependent())
3797 return;
3798 if (I->isAlignas())
3799 AlignasAttr = I;
3800 Align = std::max(Align, I->getAlignment(Context));
3801 }
3802
3803 if (AlignasAttr && Align) {
3804 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3805 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3806 if (NaturalAlign > RequestedAlign)
3807 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3808 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3809 }
3810 }
3811
checkMSInheritanceAttrOnDefinition(CXXRecordDecl * RD,SourceRange Range,bool BestCase,MSInheritanceAttr::Spelling SemanticSpelling)3812 bool Sema::checkMSInheritanceAttrOnDefinition(
3813 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3814 MSInheritanceAttr::Spelling SemanticSpelling) {
3815 assert(RD->hasDefinition() && "RD has no definition!");
3816
3817 // We may not have seen base specifiers or any virtual methods yet. We will
3818 // have to wait until the record is defined to catch any mismatches.
3819 if (!RD->getDefinition()->isCompleteDefinition())
3820 return false;
3821
3822 // The unspecified model never matches what a definition could need.
3823 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3824 return false;
3825
3826 if (BestCase) {
3827 if (RD->calculateInheritanceModel() == SemanticSpelling)
3828 return false;
3829 } else {
3830 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3831 return false;
3832 }
3833
3834 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3835 << 0 /*definition*/;
3836 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3837 << RD->getNameAsString();
3838 return true;
3839 }
3840
3841 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3842 /// attribute.
parseModeAttrArg(Sema & S,StringRef Str,unsigned & DestWidth,bool & IntegerMode,bool & ComplexMode)3843 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3844 bool &IntegerMode, bool &ComplexMode) {
3845 IntegerMode = true;
3846 ComplexMode = false;
3847 switch (Str.size()) {
3848 case 2:
3849 switch (Str[0]) {
3850 case 'Q':
3851 DestWidth = 8;
3852 break;
3853 case 'H':
3854 DestWidth = 16;
3855 break;
3856 case 'S':
3857 DestWidth = 32;
3858 break;
3859 case 'D':
3860 DestWidth = 64;
3861 break;
3862 case 'X':
3863 DestWidth = 96;
3864 break;
3865 case 'T':
3866 DestWidth = 128;
3867 break;
3868 }
3869 if (Str[1] == 'F') {
3870 IntegerMode = false;
3871 } else if (Str[1] == 'C') {
3872 IntegerMode = false;
3873 ComplexMode = true;
3874 } else if (Str[1] != 'I') {
3875 DestWidth = 0;
3876 }
3877 break;
3878 case 4:
3879 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3880 // pointer on PIC16 and other embedded platforms.
3881 if (Str == "word")
3882 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3883 else if (Str == "byte")
3884 DestWidth = S.Context.getTargetInfo().getCharWidth();
3885 break;
3886 case 7:
3887 if (Str == "pointer")
3888 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3889 break;
3890 case 11:
3891 if (Str == "unwind_word")
3892 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3893 break;
3894 }
3895 }
3896
3897 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3898 /// type.
3899 ///
3900 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3901 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3902 /// HImode, not an intermediate pointer.
handleModeAttr(Sema & S,Decl * D,const ParsedAttr & AL)3903 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3904 // This attribute isn't documented, but glibc uses it. It changes
3905 // the width of an int or unsigned int to the specified size.
3906 if (!AL.isArgIdent(0)) {
3907 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
3908 << AL << AANT_ArgumentIdentifier;
3909 return;
3910 }
3911
3912 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
3913
3914 S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex());
3915 }
3916
AddModeAttr(SourceRange AttrRange,Decl * D,IdentifierInfo * Name,unsigned SpellingListIndex,bool InInstantiation)3917 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3918 unsigned SpellingListIndex, bool InInstantiation) {
3919 StringRef Str = Name->getName();
3920 normalizeName(Str);
3921 SourceLocation AttrLoc = AttrRange.getBegin();
3922
3923 unsigned DestWidth = 0;
3924 bool IntegerMode = true;
3925 bool ComplexMode = false;
3926 llvm::APInt VectorSize(64, 0);
3927 if (Str.size() >= 4 && Str[0] == 'V') {
3928 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3929 size_t StrSize = Str.size();
3930 size_t VectorStringLength = 0;
3931 while ((VectorStringLength + 1) < StrSize &&
3932 isdigit(Str[VectorStringLength + 1]))
3933 ++VectorStringLength;
3934 if (VectorStringLength &&
3935 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3936 VectorSize.isPowerOf2()) {
3937 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3938 IntegerMode, ComplexMode);
3939 // Avoid duplicate warning from template instantiation.
3940 if (!InInstantiation)
3941 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3942 } else {
3943 VectorSize = 0;
3944 }
3945 }
3946
3947 if (!VectorSize)
3948 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3949
3950 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3951 // and friends, at least with glibc.
3952 // FIXME: Make sure floating-point mappings are accurate
3953 // FIXME: Support XF and TF types
3954 if (!DestWidth) {
3955 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3956 return;
3957 }
3958
3959 QualType OldTy;
3960 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3961 OldTy = TD->getUnderlyingType();
3962 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
3963 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3964 // Try to get type from enum declaration, default to int.
3965 OldTy = ED->getIntegerType();
3966 if (OldTy.isNull())
3967 OldTy = Context.IntTy;
3968 } else
3969 OldTy = cast<ValueDecl>(D)->getType();
3970
3971 if (OldTy->isDependentType()) {
3972 D->addAttr(::new (Context)
3973 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3974 return;
3975 }
3976
3977 // Base type can also be a vector type (see PR17453).
3978 // Distinguish between base type and base element type.
3979 QualType OldElemTy = OldTy;
3980 if (const auto *VT = OldTy->getAs<VectorType>())
3981 OldElemTy = VT->getElementType();
3982
3983 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3984 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3985 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3986 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3987 VectorSize.getBoolValue()) {
3988 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3989 return;
3990 }
3991 bool IntegralOrAnyEnumType =
3992 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3993
3994 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3995 !IntegralOrAnyEnumType)
3996 Diag(AttrLoc, diag::err_mode_not_primitive);
3997 else if (IntegerMode) {
3998 if (!IntegralOrAnyEnumType)
3999 Diag(AttrLoc, diag::err_mode_wrong_type);
4000 } else if (ComplexMode) {
4001 if (!OldElemTy->isComplexType())
4002 Diag(AttrLoc, diag::err_mode_wrong_type);
4003 } else {
4004 if (!OldElemTy->isFloatingType())
4005 Diag(AttrLoc, diag::err_mode_wrong_type);
4006 }
4007
4008 QualType NewElemTy;
4009
4010 if (IntegerMode)
4011 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4012 OldElemTy->isSignedIntegerType());
4013 else
4014 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
4015
4016 if (NewElemTy.isNull()) {
4017 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4018 return;
4019 }
4020
4021 if (ComplexMode) {
4022 NewElemTy = Context.getComplexType(NewElemTy);
4023 }
4024
4025 QualType NewTy = NewElemTy;
4026 if (VectorSize.getBoolValue()) {
4027 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4028 VectorType::GenericVector);
4029 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4030 // Complex machine mode does not support base vector types.
4031 if (ComplexMode) {
4032 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4033 return;
4034 }
4035 unsigned NumElements = Context.getTypeSize(OldElemTy) *
4036 OldVT->getNumElements() /
4037 Context.getTypeSize(NewElemTy);
4038 NewTy =
4039 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4040 }
4041
4042 if (NewTy.isNull()) {
4043 Diag(AttrLoc, diag::err_mode_wrong_type);
4044 return;
4045 }
4046
4047 // Install the new type.
4048 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4049 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4050 else if (auto *ED = dyn_cast<EnumDecl>(D))
4051 ED->setIntegerType(NewTy);
4052 else
4053 cast<ValueDecl>(D)->setType(NewTy);
4054
4055 D->addAttr(::new (Context)
4056 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
4057 }
4058
handleNoDebugAttr(Sema & S,Decl * D,const ParsedAttr & AL)4059 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4060 D->addAttr(::new (S.Context)
4061 NoDebugAttr(AL.getRange(), S.Context,
4062 AL.getAttributeSpellingListIndex()));
4063 }
4064
mergeAlwaysInlineAttr(Decl * D,SourceRange Range,IdentifierInfo * Ident,unsigned AttrSpellingListIndex)4065 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
4066 IdentifierInfo *Ident,
4067 unsigned AttrSpellingListIndex) {
4068 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4069 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
4070 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4071 return nullptr;
4072 }
4073
4074 if (D->hasAttr<AlwaysInlineAttr>())
4075 return nullptr;
4076
4077 return ::new (Context) AlwaysInlineAttr(Range, Context,
4078 AttrSpellingListIndex);
4079 }
4080
mergeCommonAttr(Decl * D,const ParsedAttr & AL)4081 CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4082 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4083 return nullptr;
4084
4085 return ::new (Context)
4086 CommonAttr(AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4087 }
4088
mergeCommonAttr(Decl * D,const CommonAttr & AL)4089 CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4090 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4091 return nullptr;
4092
4093 return ::new (Context)
4094 CommonAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4095 }
4096
mergeInternalLinkageAttr(Decl * D,const ParsedAttr & AL)4097 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4098 const ParsedAttr &AL) {
4099 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4100 // Attribute applies to Var but not any subclass of it (like ParmVar,
4101 // ImplicitParm or VarTemplateSpecialization).
4102 if (VD->getKind() != Decl::Var) {
4103 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4104 << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4105 : ExpectedVariableOrFunction);
4106 return nullptr;
4107 }
4108 // Attribute does not apply to non-static local variables.
4109 if (VD->hasLocalStorage()) {
4110 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4111 return nullptr;
4112 }
4113 }
4114
4115 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4116 return nullptr;
4117
4118 return ::new (Context) InternalLinkageAttr(
4119 AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4120 }
4121 InternalLinkageAttr *
mergeInternalLinkageAttr(Decl * D,const InternalLinkageAttr & AL)4122 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4123 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4124 // Attribute applies to Var but not any subclass of it (like ParmVar,
4125 // ImplicitParm or VarTemplateSpecialization).
4126 if (VD->getKind() != Decl::Var) {
4127 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4128 << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4129 : ExpectedVariableOrFunction);
4130 return nullptr;
4131 }
4132 // Attribute does not apply to non-static local variables.
4133 if (VD->hasLocalStorage()) {
4134 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4135 return nullptr;
4136 }
4137 }
4138
4139 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4140 return nullptr;
4141
4142 return ::new (Context)
4143 InternalLinkageAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4144 }
4145
mergeMinSizeAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex)4146 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4147 unsigned AttrSpellingListIndex) {
4148 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4149 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4150 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4151 return nullptr;
4152 }
4153
4154 if (D->hasAttr<MinSizeAttr>())
4155 return nullptr;
4156
4157 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4158 }
4159
mergeOptimizeNoneAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex)4160 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4161 unsigned AttrSpellingListIndex) {
4162 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4163 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4164 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4165 D->dropAttr<AlwaysInlineAttr>();
4166 }
4167 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4168 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4169 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4170 D->dropAttr<MinSizeAttr>();
4171 }
4172
4173 if (D->hasAttr<OptimizeNoneAttr>())
4174 return nullptr;
4175
4176 return ::new (Context) OptimizeNoneAttr(Range, Context,
4177 AttrSpellingListIndex);
4178 }
4179
handleAlwaysInlineAttr(Sema & S,Decl * D,const ParsedAttr & AL)4180 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4181 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4182 return;
4183
4184 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4185 D, AL.getRange(), AL.getName(),
4186 AL.getAttributeSpellingListIndex()))
4187 D->addAttr(Inline);
4188 }
4189
handleMinSizeAttr(Sema & S,Decl * D,const ParsedAttr & AL)4190 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4191 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4192 D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4193 D->addAttr(MinSize);
4194 }
4195
handleOptimizeNoneAttr(Sema & S,Decl * D,const ParsedAttr & AL)4196 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4197 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4198 D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4199 D->addAttr(Optnone);
4200 }
4201
handleConstantAttr(Sema & S,Decl * D,const ParsedAttr & AL)4202 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4203 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4204 return;
4205 const auto *VD = cast<VarDecl>(D);
4206 if (!VD->hasGlobalStorage()) {
4207 S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4208 return;
4209 }
4210 D->addAttr(::new (S.Context) CUDAConstantAttr(
4211 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4212 }
4213
handleSharedAttr(Sema & S,Decl * D,const ParsedAttr & AL)4214 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4215 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4216 return;
4217 const auto *VD = cast<VarDecl>(D);
4218 // extern __shared__ is only allowed on arrays with no length (e.g.
4219 // "int x[]").
4220 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4221 !isa<IncompleteArrayType>(VD->getType())) {
4222 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4223 return;
4224 }
4225 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4226 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4227 << S.CurrentCUDATarget())
4228 return;
4229 D->addAttr(::new (S.Context) CUDASharedAttr(
4230 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4231 }
4232
handleGlobalAttr(Sema & S,Decl * D,const ParsedAttr & AL)4233 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4234 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4235 checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4236 return;
4237 }
4238 const auto *FD = cast<FunctionDecl>(D);
4239 if (!FD->getReturnType()->isVoidType()) {
4240 SourceRange RTRange = FD->getReturnTypeSourceRange();
4241 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4242 << FD->getType()
4243 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4244 : FixItHint());
4245 return;
4246 }
4247 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4248 if (Method->isInstance()) {
4249 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4250 << Method;
4251 return;
4252 }
4253 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4254 }
4255 // Only warn for "inline" when compiling for host, to cut down on noise.
4256 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4257 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4258
4259 D->addAttr(::new (S.Context)
4260 CUDAGlobalAttr(AL.getRange(), S.Context,
4261 AL.getAttributeSpellingListIndex()));
4262 }
4263
handleGNUInlineAttr(Sema & S,Decl * D,const ParsedAttr & AL)4264 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4265 const auto *Fn = cast<FunctionDecl>(D);
4266 if (!Fn->isInlineSpecified()) {
4267 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4268 return;
4269 }
4270
4271 D->addAttr(::new (S.Context)
4272 GNUInlineAttr(AL.getRange(), S.Context,
4273 AL.getAttributeSpellingListIndex()));
4274 }
4275
handleCallConvAttr(Sema & S,Decl * D,const ParsedAttr & AL)4276 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4277 if (hasDeclarator(D)) return;
4278
4279 // Diagnostic is emitted elsewhere: here we store the (valid) AL
4280 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4281 CallingConv CC;
4282 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4283 return;
4284
4285 if (!isa<ObjCMethodDecl>(D)) {
4286 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4287 << AL << ExpectedFunctionOrMethod;
4288 return;
4289 }
4290
4291 switch (AL.getKind()) {
4292 case ParsedAttr::AT_FastCall:
4293 D->addAttr(::new (S.Context)
4294 FastCallAttr(AL.getRange(), S.Context,
4295 AL.getAttributeSpellingListIndex()));
4296 return;
4297 case ParsedAttr::AT_StdCall:
4298 D->addAttr(::new (S.Context)
4299 StdCallAttr(AL.getRange(), S.Context,
4300 AL.getAttributeSpellingListIndex()));
4301 return;
4302 case ParsedAttr::AT_ThisCall:
4303 D->addAttr(::new (S.Context)
4304 ThisCallAttr(AL.getRange(), S.Context,
4305 AL.getAttributeSpellingListIndex()));
4306 return;
4307 case ParsedAttr::AT_CDecl:
4308 D->addAttr(::new (S.Context)
4309 CDeclAttr(AL.getRange(), S.Context,
4310 AL.getAttributeSpellingListIndex()));
4311 return;
4312 case ParsedAttr::AT_Pascal:
4313 D->addAttr(::new (S.Context)
4314 PascalAttr(AL.getRange(), S.Context,
4315 AL.getAttributeSpellingListIndex()));
4316 return;
4317 case ParsedAttr::AT_SwiftCall:
4318 D->addAttr(::new (S.Context)
4319 SwiftCallAttr(AL.getRange(), S.Context,
4320 AL.getAttributeSpellingListIndex()));
4321 return;
4322 case ParsedAttr::AT_VectorCall:
4323 D->addAttr(::new (S.Context)
4324 VectorCallAttr(AL.getRange(), S.Context,
4325 AL.getAttributeSpellingListIndex()));
4326 return;
4327 case ParsedAttr::AT_MSABI:
4328 D->addAttr(::new (S.Context)
4329 MSABIAttr(AL.getRange(), S.Context,
4330 AL.getAttributeSpellingListIndex()));
4331 return;
4332 case ParsedAttr::AT_SysVABI:
4333 D->addAttr(::new (S.Context)
4334 SysVABIAttr(AL.getRange(), S.Context,
4335 AL.getAttributeSpellingListIndex()));
4336 return;
4337 case ParsedAttr::AT_RegCall:
4338 D->addAttr(::new (S.Context) RegCallAttr(
4339 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4340 return;
4341 case ParsedAttr::AT_Pcs: {
4342 PcsAttr::PCSType PCS;
4343 switch (CC) {
4344 case CC_AAPCS:
4345 PCS = PcsAttr::AAPCS;
4346 break;
4347 case CC_AAPCS_VFP:
4348 PCS = PcsAttr::AAPCS_VFP;
4349 break;
4350 default:
4351 llvm_unreachable("unexpected calling convention in pcs attribute");
4352 }
4353
4354 D->addAttr(::new (S.Context)
4355 PcsAttr(AL.getRange(), S.Context, PCS,
4356 AL.getAttributeSpellingListIndex()));
4357 return;
4358 }
4359 case ParsedAttr::AT_AArch64VectorPcs:
4360 D->addAttr(::new(S.Context)
4361 AArch64VectorPcsAttr(AL.getRange(), S.Context,
4362 AL.getAttributeSpellingListIndex()));
4363 return;
4364 case ParsedAttr::AT_IntelOclBicc:
4365 D->addAttr(::new (S.Context)
4366 IntelOclBiccAttr(AL.getRange(), S.Context,
4367 AL.getAttributeSpellingListIndex()));
4368 return;
4369 case ParsedAttr::AT_PreserveMost:
4370 D->addAttr(::new (S.Context) PreserveMostAttr(
4371 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4372 return;
4373 case ParsedAttr::AT_PreserveAll:
4374 D->addAttr(::new (S.Context) PreserveAllAttr(
4375 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4376 return;
4377 default:
4378 llvm_unreachable("unexpected attribute kind");
4379 }
4380 }
4381
handleSuppressAttr(Sema & S,Decl * D,const ParsedAttr & AL)4382 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4383 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4384 return;
4385
4386 std::vector<StringRef> DiagnosticIdentifiers;
4387 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4388 StringRef RuleName;
4389
4390 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4391 return;
4392
4393 // FIXME: Warn if the rule name is unknown. This is tricky because only
4394 // clang-tidy knows about available rules.
4395 DiagnosticIdentifiers.push_back(RuleName);
4396 }
4397 D->addAttr(::new (S.Context) SuppressAttr(
4398 AL.getRange(), S.Context, DiagnosticIdentifiers.data(),
4399 DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex()));
4400 }
4401
CheckCallingConvAttr(const ParsedAttr & Attrs,CallingConv & CC,const FunctionDecl * FD)4402 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4403 const FunctionDecl *FD) {
4404 if (Attrs.isInvalid())
4405 return true;
4406
4407 if (Attrs.hasProcessingCache()) {
4408 CC = (CallingConv) Attrs.getProcessingCache();
4409 return false;
4410 }
4411
4412 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4413 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4414 Attrs.setInvalid();
4415 return true;
4416 }
4417
4418 // TODO: diagnose uses of these conventions on the wrong target.
4419 switch (Attrs.getKind()) {
4420 case ParsedAttr::AT_CDecl:
4421 CC = CC_C;
4422 break;
4423 case ParsedAttr::AT_FastCall:
4424 CC = CC_X86FastCall;
4425 break;
4426 case ParsedAttr::AT_StdCall:
4427 CC = CC_X86StdCall;
4428 break;
4429 case ParsedAttr::AT_ThisCall:
4430 CC = CC_X86ThisCall;
4431 break;
4432 case ParsedAttr::AT_Pascal:
4433 CC = CC_X86Pascal;
4434 break;
4435 case ParsedAttr::AT_SwiftCall:
4436 CC = CC_Swift;
4437 break;
4438 case ParsedAttr::AT_VectorCall:
4439 CC = CC_X86VectorCall;
4440 break;
4441 case ParsedAttr::AT_AArch64VectorPcs:
4442 CC = CC_AArch64VectorCall;
4443 break;
4444 case ParsedAttr::AT_RegCall:
4445 CC = CC_X86RegCall;
4446 break;
4447 case ParsedAttr::AT_MSABI:
4448 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4449 CC_Win64;
4450 break;
4451 case ParsedAttr::AT_SysVABI:
4452 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4453 CC_C;
4454 break;
4455 case ParsedAttr::AT_Pcs: {
4456 StringRef StrRef;
4457 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4458 Attrs.setInvalid();
4459 return true;
4460 }
4461 if (StrRef == "aapcs") {
4462 CC = CC_AAPCS;
4463 break;
4464 } else if (StrRef == "aapcs-vfp") {
4465 CC = CC_AAPCS_VFP;
4466 break;
4467 }
4468
4469 Attrs.setInvalid();
4470 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4471 return true;
4472 }
4473 case ParsedAttr::AT_IntelOclBicc:
4474 CC = CC_IntelOclBicc;
4475 break;
4476 case ParsedAttr::AT_PreserveMost:
4477 CC = CC_PreserveMost;
4478 break;
4479 case ParsedAttr::AT_PreserveAll:
4480 CC = CC_PreserveAll;
4481 break;
4482 default: llvm_unreachable("unexpected attribute kind");
4483 }
4484
4485 const TargetInfo &TI = Context.getTargetInfo();
4486 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4487 if (A != TargetInfo::CCCR_OK) {
4488 if (A == TargetInfo::CCCR_Warning)
4489 Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs;
4490
4491 // This convention is not valid for the target. Use the default function or
4492 // method calling convention.
4493 bool IsCXXMethod = false, IsVariadic = false;
4494 if (FD) {
4495 IsCXXMethod = FD->isCXXInstanceMember();
4496 IsVariadic = FD->isVariadic();
4497 }
4498 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4499 }
4500
4501 Attrs.setProcessingCache((unsigned) CC);
4502 return false;
4503 }
4504
4505 /// Pointer-like types in the default address space.
isValidSwiftContextType(QualType Ty)4506 static bool isValidSwiftContextType(QualType Ty) {
4507 if (!Ty->hasPointerRepresentation())
4508 return Ty->isDependentType();
4509 return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4510 }
4511
4512 /// Pointers and references in the default address space.
isValidSwiftIndirectResultType(QualType Ty)4513 static bool isValidSwiftIndirectResultType(QualType Ty) {
4514 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4515 Ty = PtrType->getPointeeType();
4516 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4517 Ty = RefType->getPointeeType();
4518 } else {
4519 return Ty->isDependentType();
4520 }
4521 return Ty.getAddressSpace() == LangAS::Default;
4522 }
4523
4524 /// Pointers and references to pointers in the default address space.
isValidSwiftErrorResultType(QualType Ty)4525 static bool isValidSwiftErrorResultType(QualType Ty) {
4526 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4527 Ty = PtrType->getPointeeType();
4528 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4529 Ty = RefType->getPointeeType();
4530 } else {
4531 return Ty->isDependentType();
4532 }
4533 if (!Ty.getQualifiers().empty())
4534 return false;
4535 return isValidSwiftContextType(Ty);
4536 }
4537
handleParameterABIAttr(Sema & S,Decl * D,const ParsedAttr & Attrs,ParameterABI Abi)4538 static void handleParameterABIAttr(Sema &S, Decl *D, const ParsedAttr &Attrs,
4539 ParameterABI Abi) {
4540 S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4541 Attrs.getAttributeSpellingListIndex());
4542 }
4543
AddParameterABIAttr(SourceRange range,Decl * D,ParameterABI abi,unsigned spellingIndex)4544 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4545 unsigned spellingIndex) {
4546
4547 QualType type = cast<ParmVarDecl>(D)->getType();
4548
4549 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4550 if (existingAttr->getABI() != abi) {
4551 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4552 << getParameterABISpelling(abi) << existingAttr;
4553 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4554 return;
4555 }
4556 }
4557
4558 switch (abi) {
4559 case ParameterABI::Ordinary:
4560 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4561
4562 case ParameterABI::SwiftContext:
4563 if (!isValidSwiftContextType(type)) {
4564 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4565 << getParameterABISpelling(abi)
4566 << /*pointer to pointer */ 0 << type;
4567 }
4568 D->addAttr(::new (Context)
4569 SwiftContextAttr(range, Context, spellingIndex));
4570 return;
4571
4572 case ParameterABI::SwiftErrorResult:
4573 if (!isValidSwiftErrorResultType(type)) {
4574 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4575 << getParameterABISpelling(abi)
4576 << /*pointer to pointer */ 1 << type;
4577 }
4578 D->addAttr(::new (Context)
4579 SwiftErrorResultAttr(range, Context, spellingIndex));
4580 return;
4581
4582 case ParameterABI::SwiftIndirectResult:
4583 if (!isValidSwiftIndirectResultType(type)) {
4584 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4585 << getParameterABISpelling(abi)
4586 << /*pointer*/ 0 << type;
4587 }
4588 D->addAttr(::new (Context)
4589 SwiftIndirectResultAttr(range, Context, spellingIndex));
4590 return;
4591 }
4592 llvm_unreachable("bad parameter ABI attribute");
4593 }
4594
4595 /// Checks a regparm attribute, returning true if it is ill-formed and
4596 /// otherwise setting numParams to the appropriate value.
CheckRegparmAttr(const ParsedAttr & AL,unsigned & numParams)4597 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4598 if (AL.isInvalid())
4599 return true;
4600
4601 if (!checkAttributeNumArgs(*this, AL, 1)) {
4602 AL.setInvalid();
4603 return true;
4604 }
4605
4606 uint32_t NP;
4607 Expr *NumParamsExpr = AL.getArgAsExpr(0);
4608 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4609 AL.setInvalid();
4610 return true;
4611 }
4612
4613 if (Context.getTargetInfo().getRegParmMax() == 0) {
4614 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4615 << NumParamsExpr->getSourceRange();
4616 AL.setInvalid();
4617 return true;
4618 }
4619
4620 numParams = NP;
4621 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4622 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4623 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4624 AL.setInvalid();
4625 return true;
4626 }
4627
4628 return false;
4629 }
4630
4631 // Checks whether an argument of launch_bounds attribute is
4632 // acceptable, performs implicit conversion to Rvalue, and returns
4633 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4634 // and may output an error.
makeLaunchBoundsArgExpr(Sema & S,Expr * E,const CUDALaunchBoundsAttr & AL,const unsigned Idx)4635 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4636 const CUDALaunchBoundsAttr &AL,
4637 const unsigned Idx) {
4638 if (S.DiagnoseUnexpandedParameterPack(E))
4639 return nullptr;
4640
4641 // Accept template arguments for now as they depend on something else.
4642 // We'll get to check them when they eventually get instantiated.
4643 if (E->isValueDependent())
4644 return E;
4645
4646 llvm::APSInt I(64);
4647 if (!E->isIntegerConstantExpr(I, S.Context)) {
4648 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4649 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4650 return nullptr;
4651 }
4652 // Make sure we can fit it in 32 bits.
4653 if (!I.isIntN(32)) {
4654 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4655 << 32 << /* Unsigned */ 1;
4656 return nullptr;
4657 }
4658 if (I < 0)
4659 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4660 << &AL << Idx << E->getSourceRange();
4661
4662 // We may need to perform implicit conversion of the argument.
4663 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4664 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4665 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4666 assert(!ValArg.isInvalid() &&
4667 "Unexpected PerformCopyInitialization() failure.");
4668
4669 return ValArg.getAs<Expr>();
4670 }
4671
AddLaunchBoundsAttr(SourceRange AttrRange,Decl * D,Expr * MaxThreads,Expr * MinBlocks,unsigned SpellingListIndex)4672 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4673 Expr *MinBlocks, unsigned SpellingListIndex) {
4674 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4675 SpellingListIndex);
4676 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4677 if (MaxThreads == nullptr)
4678 return;
4679
4680 if (MinBlocks) {
4681 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4682 if (MinBlocks == nullptr)
4683 return;
4684 }
4685
4686 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4687 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4688 }
4689
handleLaunchBoundsAttr(Sema & S,Decl * D,const ParsedAttr & AL)4690 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4691 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4692 !checkAttributeAtMostNumArgs(S, AL, 2))
4693 return;
4694
4695 S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0),
4696 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
4697 AL.getAttributeSpellingListIndex());
4698 }
4699
handleArgumentWithTypeTagAttr(Sema & S,Decl * D,const ParsedAttr & AL)4700 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4701 const ParsedAttr &AL) {
4702 if (!AL.isArgIdent(0)) {
4703 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4704 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4705 return;
4706 }
4707
4708 ParamIdx ArgumentIdx;
4709 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4710 ArgumentIdx))
4711 return;
4712
4713 ParamIdx TypeTagIdx;
4714 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4715 TypeTagIdx))
4716 return;
4717
4718 bool IsPointer = AL.getName()->getName() == "pointer_with_type_tag";
4719 if (IsPointer) {
4720 // Ensure that buffer has a pointer type.
4721 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4722 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4723 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4724 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
4725 }
4726
4727 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4728 AL.getRange(), S.Context, AL.getArgAsIdent(0)->Ident, ArgumentIdx,
4729 TypeTagIdx, IsPointer, AL.getAttributeSpellingListIndex()));
4730 }
4731
handleTypeTagForDatatypeAttr(Sema & S,Decl * D,const ParsedAttr & AL)4732 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4733 const ParsedAttr &AL) {
4734 if (!AL.isArgIdent(0)) {
4735 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4736 << AL << 1 << AANT_ArgumentIdentifier;
4737 return;
4738 }
4739
4740 if (!checkAttributeNumArgs(S, AL, 1))
4741 return;
4742
4743 if (!isa<VarDecl>(D)) {
4744 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4745 << AL << ExpectedVariable;
4746 return;
4747 }
4748
4749 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4750 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4751 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4752 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4753
4754 D->addAttr(::new (S.Context)
4755 TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind,
4756 MatchingCTypeLoc,
4757 AL.getLayoutCompatible(),
4758 AL.getMustBeNull(),
4759 AL.getAttributeSpellingListIndex()));
4760 }
4761
handleXRayLogArgsAttr(Sema & S,Decl * D,const ParsedAttr & AL)4762 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4763 ParamIdx ArgCount;
4764
4765 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4766 ArgCount,
4767 true /* CanIndexImplicitThis */))
4768 return;
4769
4770 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4771 D->addAttr(::new (S.Context) XRayLogArgsAttr(
4772 AL.getRange(), S.Context, ArgCount.getSourceIndex(),
4773 AL.getAttributeSpellingListIndex()));
4774 }
4775
4776 //===----------------------------------------------------------------------===//
4777 // Checker-specific attribute handlers.
4778 //===----------------------------------------------------------------------===//
isValidSubjectOfNSReturnsRetainedAttribute(QualType QT)4779 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
4780 return QT->isDependentType() || QT->isObjCRetainableType();
4781 }
4782
isValidSubjectOfNSAttribute(QualType QT)4783 static bool isValidSubjectOfNSAttribute(QualType QT) {
4784 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
4785 QT->isObjCNSObjectType();
4786 }
4787
isValidSubjectOfCFAttribute(QualType QT)4788 static bool isValidSubjectOfCFAttribute(QualType QT) {
4789 return QT->isDependentType() || QT->isPointerType() ||
4790 isValidSubjectOfNSAttribute(QT);
4791 }
4792
isValidSubjectOfOSAttribute(QualType QT)4793 static bool isValidSubjectOfOSAttribute(QualType QT) {
4794 if (QT->isDependentType())
4795 return true;
4796 QualType PT = QT->getPointeeType();
4797 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
4798 }
4799
AddXConsumedAttr(Decl * D,SourceRange SR,unsigned SpellingIndex,RetainOwnershipKind K,bool IsTemplateInstantiation)4800 void Sema::AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex,
4801 RetainOwnershipKind K,
4802 bool IsTemplateInstantiation) {
4803 ValueDecl *VD = cast<ValueDecl>(D);
4804 switch (K) {
4805 case RetainOwnershipKind::OS:
4806 handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
4807 *this, VD, SR, SpellingIndex, isValidSubjectOfOSAttribute(VD->getType()),
4808 diag::warn_ns_attribute_wrong_parameter_type,
4809 /*ExtraArgs=*/SR, "os_consumed", /*pointers*/ 1);
4810 return;
4811 case RetainOwnershipKind::NS:
4812 handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
4813 *this, VD, SR, SpellingIndex, isValidSubjectOfNSAttribute(VD->getType()),
4814
4815 // These attributes are normally just advisory, but in ARC, ns_consumed
4816 // is significant. Allow non-dependent code to contain inappropriate
4817 // attributes even in ARC, but require template instantiations to be
4818 // set up correctly.
4819 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
4820 ? diag::err_ns_attribute_wrong_parameter_type
4821 : diag::warn_ns_attribute_wrong_parameter_type),
4822 /*ExtraArgs=*/SR, "ns_consumed", /*objc pointers*/ 0);
4823 return;
4824 case RetainOwnershipKind::CF:
4825 handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
4826 *this, VD, SR, SpellingIndex,
4827 isValidSubjectOfCFAttribute(VD->getType()),
4828 diag::warn_ns_attribute_wrong_parameter_type,
4829 /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/1);
4830 return;
4831 }
4832 }
4833
4834 static Sema::RetainOwnershipKind
parsedAttrToRetainOwnershipKind(const ParsedAttr & AL)4835 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
4836 switch (AL.getKind()) {
4837 case ParsedAttr::AT_CFConsumed:
4838 case ParsedAttr::AT_CFReturnsRetained:
4839 case ParsedAttr::AT_CFReturnsNotRetained:
4840 return Sema::RetainOwnershipKind::CF;
4841 case ParsedAttr::AT_OSConsumesThis:
4842 case ParsedAttr::AT_OSConsumed:
4843 case ParsedAttr::AT_OSReturnsRetained:
4844 case ParsedAttr::AT_OSReturnsNotRetained:
4845 case ParsedAttr::AT_OSReturnsRetainedOnZero:
4846 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
4847 return Sema::RetainOwnershipKind::OS;
4848 case ParsedAttr::AT_NSConsumesSelf:
4849 case ParsedAttr::AT_NSConsumed:
4850 case ParsedAttr::AT_NSReturnsRetained:
4851 case ParsedAttr::AT_NSReturnsNotRetained:
4852 case ParsedAttr::AT_NSReturnsAutoreleased:
4853 return Sema::RetainOwnershipKind::NS;
4854 default:
4855 llvm_unreachable("Wrong argument supplied");
4856 }
4857 }
4858
checkNSReturnsRetainedReturnType(SourceLocation Loc,QualType QT)4859 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
4860 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
4861 return false;
4862
4863 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
4864 << "'ns_returns_retained'" << 0 << 0;
4865 return true;
4866 }
4867
4868 /// \return whether the parameter is a pointer to OSObject pointer.
isValidOSObjectOutParameter(const Decl * D)4869 static bool isValidOSObjectOutParameter(const Decl *D) {
4870 const auto *PVD = dyn_cast<ParmVarDecl>(D);
4871 if (!PVD)
4872 return false;
4873 QualType QT = PVD->getType();
4874 QualType PT = QT->getPointeeType();
4875 return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
4876 }
4877
handleXReturnsXRetainedAttr(Sema & S,Decl * D,const ParsedAttr & AL)4878 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
4879 const ParsedAttr &AL) {
4880 QualType ReturnType;
4881 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
4882
4883 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
4884 ReturnType = MD->getReturnType();
4885 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4886 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
4887 return; // ignore: was handled as a type attribute
4888 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
4889 ReturnType = PD->getType();
4890 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4891 ReturnType = FD->getReturnType();
4892 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
4893 // Attributes on parameters are used for out-parameters,
4894 // passed as pointers-to-pointers.
4895 unsigned DiagID = K == Sema::RetainOwnershipKind::CF
4896 ? /*pointer-to-CF-pointer*/2
4897 : /*pointer-to-OSObject-pointer*/3;
4898 ReturnType = Param->getType()->getPointeeType();
4899 if (ReturnType.isNull()) {
4900 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
4901 << AL << DiagID << AL.getRange();
4902 return;
4903 }
4904 } else if (AL.isUsedAsTypeAttr()) {
4905 return;
4906 } else {
4907 AttributeDeclKind ExpectedDeclKind;
4908 switch (AL.getKind()) {
4909 default: llvm_unreachable("invalid ownership attribute");
4910 case ParsedAttr::AT_NSReturnsRetained:
4911 case ParsedAttr::AT_NSReturnsAutoreleased:
4912 case ParsedAttr::AT_NSReturnsNotRetained:
4913 ExpectedDeclKind = ExpectedFunctionOrMethod;
4914 break;
4915
4916 case ParsedAttr::AT_OSReturnsRetained:
4917 case ParsedAttr::AT_OSReturnsNotRetained:
4918 case ParsedAttr::AT_CFReturnsRetained:
4919 case ParsedAttr::AT_CFReturnsNotRetained:
4920 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4921 break;
4922 }
4923 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
4924 << AL.getRange() << AL << ExpectedDeclKind;
4925 return;
4926 }
4927
4928 bool TypeOK;
4929 bool Cf;
4930 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
4931 switch (AL.getKind()) {
4932 default: llvm_unreachable("invalid ownership attribute");
4933 case ParsedAttr::AT_NSReturnsRetained:
4934 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
4935 Cf = false;
4936 break;
4937
4938 case ParsedAttr::AT_NSReturnsAutoreleased:
4939 case ParsedAttr::AT_NSReturnsNotRetained:
4940 TypeOK = isValidSubjectOfNSAttribute(ReturnType);
4941 Cf = false;
4942 break;
4943
4944 case ParsedAttr::AT_CFReturnsRetained:
4945 case ParsedAttr::AT_CFReturnsNotRetained:
4946 TypeOK = isValidSubjectOfCFAttribute(ReturnType);
4947 Cf = true;
4948 break;
4949
4950 case ParsedAttr::AT_OSReturnsRetained:
4951 case ParsedAttr::AT_OSReturnsNotRetained:
4952 TypeOK = isValidSubjectOfOSAttribute(ReturnType);
4953 Cf = true;
4954 ParmDiagID = 3; // Pointer-to-OSObject-pointer
4955 break;
4956 }
4957
4958 if (!TypeOK) {
4959 if (AL.isUsedAsTypeAttr())
4960 return;
4961
4962 if (isa<ParmVarDecl>(D)) {
4963 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
4964 << AL << ParmDiagID << AL.getRange();
4965 } else {
4966 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4967 enum : unsigned {
4968 Function,
4969 Method,
4970 Property
4971 } SubjectKind = Function;
4972 if (isa<ObjCMethodDecl>(D))
4973 SubjectKind = Method;
4974 else if (isa<ObjCPropertyDecl>(D))
4975 SubjectKind = Property;
4976 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
4977 << AL << SubjectKind << Cf << AL.getRange();
4978 }
4979 return;
4980 }
4981
4982 switch (AL.getKind()) {
4983 default:
4984 llvm_unreachable("invalid ownership attribute");
4985 case ParsedAttr::AT_NSReturnsAutoreleased:
4986 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
4987 return;
4988 case ParsedAttr::AT_CFReturnsNotRetained:
4989 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
4990 return;
4991 case ParsedAttr::AT_NSReturnsNotRetained:
4992 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
4993 return;
4994 case ParsedAttr::AT_CFReturnsRetained:
4995 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
4996 return;
4997 case ParsedAttr::AT_NSReturnsRetained:
4998 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
4999 return;
5000 case ParsedAttr::AT_OSReturnsRetained:
5001 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5002 return;
5003 case ParsedAttr::AT_OSReturnsNotRetained:
5004 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5005 return;
5006 };
5007 }
5008
handleObjCReturnsInnerPointerAttr(Sema & S,Decl * D,const ParsedAttr & Attrs)5009 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5010 const ParsedAttr &Attrs) {
5011 const int EP_ObjCMethod = 1;
5012 const int EP_ObjCProperty = 2;
5013
5014 SourceLocation loc = Attrs.getLoc();
5015 QualType resultType;
5016 if (isa<ObjCMethodDecl>(D))
5017 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5018 else
5019 resultType = cast<ObjCPropertyDecl>(D)->getType();
5020
5021 if (!resultType->isReferenceType() &&
5022 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5023 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5024 << SourceRange(loc) << Attrs
5025 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5026 << /*non-retainable pointer*/ 2;
5027
5028 // Drop the attribute.
5029 return;
5030 }
5031
5032 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
5033 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5034 }
5035
handleObjCRequiresSuperAttr(Sema & S,Decl * D,const ParsedAttr & Attrs)5036 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5037 const ParsedAttr &Attrs) {
5038 const auto *Method = cast<ObjCMethodDecl>(D);
5039
5040 const DeclContext *DC = Method->getDeclContext();
5041 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5042 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5043 << 0;
5044 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5045 return;
5046 }
5047 if (Method->getMethodFamily() == OMF_dealloc) {
5048 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5049 << 1;
5050 return;
5051 }
5052
5053 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(
5054 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5055 }
5056
handleObjCBridgeAttr(Sema & S,Decl * D,const ParsedAttr & AL)5057 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5058 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5059
5060 if (!Parm) {
5061 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5062 return;
5063 }
5064
5065 // Typedefs only allow objc_bridge(id) and have some additional checking.
5066 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5067 if (!Parm->Ident->isStr("id")) {
5068 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5069 return;
5070 }
5071
5072 // Only allow 'cv void *'.
5073 QualType T = TD->getUnderlyingType();
5074 if (!T->isVoidPointerType()) {
5075 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5076 return;
5077 }
5078 }
5079
5080 D->addAttr(::new (S.Context)
5081 ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident,
5082 AL.getAttributeSpellingListIndex()));
5083 }
5084
handleObjCBridgeMutableAttr(Sema & S,Decl * D,const ParsedAttr & AL)5085 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5086 const ParsedAttr &AL) {
5087 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5088
5089 if (!Parm) {
5090 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5091 return;
5092 }
5093
5094 D->addAttr(::new (S.Context)
5095 ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident,
5096 AL.getAttributeSpellingListIndex()));
5097 }
5098
handleObjCBridgeRelatedAttr(Sema & S,Decl * D,const ParsedAttr & AL)5099 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5100 const ParsedAttr &AL) {
5101 IdentifierInfo *RelatedClass =
5102 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5103 if (!RelatedClass) {
5104 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5105 return;
5106 }
5107 IdentifierInfo *ClassMethod =
5108 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5109 IdentifierInfo *InstanceMethod =
5110 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5111 D->addAttr(::new (S.Context)
5112 ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass,
5113 ClassMethod, InstanceMethod,
5114 AL.getAttributeSpellingListIndex()));
5115 }
5116
handleObjCDesignatedInitializer(Sema & S,Decl * D,const ParsedAttr & AL)5117 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5118 const ParsedAttr &AL) {
5119 DeclContext *Ctx = D->getDeclContext();
5120
5121 // This attribute can only be applied to methods in interfaces or class
5122 // extensions.
5123 if (!isa<ObjCInterfaceDecl>(Ctx) &&
5124 !(isa<ObjCCategoryDecl>(Ctx) &&
5125 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5126 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5127 return;
5128 }
5129
5130 ObjCInterfaceDecl *IFace;
5131 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5132 IFace = CatDecl->getClassInterface();
5133 else
5134 IFace = cast<ObjCInterfaceDecl>(Ctx);
5135
5136 if (!IFace)
5137 return;
5138
5139 IFace->setHasDesignatedInitializers();
5140 D->addAttr(::new (S.Context)
5141 ObjCDesignatedInitializerAttr(AL.getRange(), S.Context,
5142 AL.getAttributeSpellingListIndex()));
5143 }
5144
handleObjCRuntimeName(Sema & S,Decl * D,const ParsedAttr & AL)5145 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5146 StringRef MetaDataName;
5147 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5148 return;
5149 D->addAttr(::new (S.Context)
5150 ObjCRuntimeNameAttr(AL.getRange(), S.Context,
5151 MetaDataName,
5152 AL.getAttributeSpellingListIndex()));
5153 }
5154
5155 // When a user wants to use objc_boxable with a union or struct
5156 // but they don't have access to the declaration (legacy/third-party code)
5157 // then they can 'enable' this feature with a typedef:
5158 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
handleObjCBoxable(Sema & S,Decl * D,const ParsedAttr & AL)5159 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5160 bool notify = false;
5161
5162 auto *RD = dyn_cast<RecordDecl>(D);
5163 if (RD && RD->getDefinition()) {
5164 RD = RD->getDefinition();
5165 notify = true;
5166 }
5167
5168 if (RD) {
5169 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5170 ObjCBoxableAttr(AL.getRange(), S.Context,
5171 AL.getAttributeSpellingListIndex());
5172 RD->addAttr(BoxableAttr);
5173 if (notify) {
5174 // we need to notify ASTReader/ASTWriter about
5175 // modification of existing declaration
5176 if (ASTMutationListener *L = S.getASTMutationListener())
5177 L->AddedAttributeToRecord(BoxableAttr, RD);
5178 }
5179 }
5180 }
5181
handleObjCOwnershipAttr(Sema & S,Decl * D,const ParsedAttr & AL)5182 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5183 if (hasDeclarator(D)) return;
5184
5185 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5186 << AL.getRange() << AL << ExpectedVariable;
5187 }
5188
handleObjCPreciseLifetimeAttr(Sema & S,Decl * D,const ParsedAttr & AL)5189 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5190 const ParsedAttr &AL) {
5191 const auto *VD = cast<ValueDecl>(D);
5192 QualType QT = VD->getType();
5193
5194 if (!QT->isDependentType() &&
5195 !QT->isObjCLifetimeType()) {
5196 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5197 << QT;
5198 return;
5199 }
5200
5201 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5202
5203 // If we have no lifetime yet, check the lifetime we're presumably
5204 // going to infer.
5205 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5206 Lifetime = QT->getObjCARCImplicitLifetime();
5207
5208 switch (Lifetime) {
5209 case Qualifiers::OCL_None:
5210 assert(QT->isDependentType() &&
5211 "didn't infer lifetime for non-dependent type?");
5212 break;
5213
5214 case Qualifiers::OCL_Weak: // meaningful
5215 case Qualifiers::OCL_Strong: // meaningful
5216 break;
5217
5218 case Qualifiers::OCL_ExplicitNone:
5219 case Qualifiers::OCL_Autoreleasing:
5220 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5221 << (Lifetime == Qualifiers::OCL_Autoreleasing);
5222 break;
5223 }
5224
5225 D->addAttr(::new (S.Context)
5226 ObjCPreciseLifetimeAttr(AL.getRange(), S.Context,
5227 AL.getAttributeSpellingListIndex()));
5228 }
5229
5230 //===----------------------------------------------------------------------===//
5231 // Microsoft specific attribute handlers.
5232 //===----------------------------------------------------------------------===//
5233
mergeUuidAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex,StringRef Uuid)5234 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5235 unsigned AttrSpellingListIndex, StringRef Uuid) {
5236 if (const auto *UA = D->getAttr<UuidAttr>()) {
5237 if (UA->getGuid().equals_lower(Uuid))
5238 return nullptr;
5239 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5240 Diag(Range.getBegin(), diag::note_previous_uuid);
5241 D->dropAttr<UuidAttr>();
5242 }
5243
5244 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5245 }
5246
handleUuidAttr(Sema & S,Decl * D,const ParsedAttr & AL)5247 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5248 if (!S.LangOpts.CPlusPlus) {
5249 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5250 << AL << AttributeLangSupport::C;
5251 return;
5252 }
5253
5254 StringRef StrRef;
5255 SourceLocation LiteralLoc;
5256 if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
5257 return;
5258
5259 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5260 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5261 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5262 StrRef = StrRef.drop_front().drop_back();
5263
5264 // Validate GUID length.
5265 if (StrRef.size() != 36) {
5266 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5267 return;
5268 }
5269
5270 for (unsigned i = 0; i < 36; ++i) {
5271 if (i == 8 || i == 13 || i == 18 || i == 23) {
5272 if (StrRef[i] != '-') {
5273 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5274 return;
5275 }
5276 } else if (!isHexDigit(StrRef[i])) {
5277 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5278 return;
5279 }
5280 }
5281
5282 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5283 // the only thing in the [] list, the [] too), and add an insertion of
5284 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5285 // separating attributes nor of the [ and the ] are in the AST.
5286 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5287 // on cfe-dev.
5288 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5289 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5290
5291 UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(),
5292 AL.getAttributeSpellingListIndex(), StrRef);
5293 if (UA)
5294 D->addAttr(UA);
5295 }
5296
handleMSInheritanceAttr(Sema & S,Decl * D,const ParsedAttr & AL)5297 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5298 if (!S.LangOpts.CPlusPlus) {
5299 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5300 << AL << AttributeLangSupport::C;
5301 return;
5302 }
5303 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5304 D, AL.getRange(), /*BestCase=*/true,
5305 AL.getAttributeSpellingListIndex(),
5306 (MSInheritanceAttr::Spelling)AL.getSemanticSpelling());
5307 if (IA) {
5308 D->addAttr(IA);
5309 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5310 }
5311 }
5312
handleDeclspecThreadAttr(Sema & S,Decl * D,const ParsedAttr & AL)5313 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5314 const auto *VD = cast<VarDecl>(D);
5315 if (!S.Context.getTargetInfo().isTLSSupported()) {
5316 S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5317 return;
5318 }
5319 if (VD->getTSCSpec() != TSCS_unspecified) {
5320 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5321 return;
5322 }
5323 if (VD->hasLocalStorage()) {
5324 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5325 return;
5326 }
5327 D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context,
5328 AL.getAttributeSpellingListIndex()));
5329 }
5330
handleAbiTagAttr(Sema & S,Decl * D,const ParsedAttr & AL)5331 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5332 SmallVector<StringRef, 4> Tags;
5333 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5334 StringRef Tag;
5335 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5336 return;
5337 Tags.push_back(Tag);
5338 }
5339
5340 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5341 if (!NS->isInline()) {
5342 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5343 return;
5344 }
5345 if (NS->isAnonymousNamespace()) {
5346 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5347 return;
5348 }
5349 if (AL.getNumArgs() == 0)
5350 Tags.push_back(NS->getName());
5351 } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5352 return;
5353
5354 // Store tags sorted and without duplicates.
5355 llvm::sort(Tags);
5356 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5357
5358 D->addAttr(::new (S.Context)
5359 AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(),
5360 AL.getAttributeSpellingListIndex()));
5361 }
5362
handleARMInterruptAttr(Sema & S,Decl * D,const ParsedAttr & AL)5363 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5364 // Check the attribute arguments.
5365 if (AL.getNumArgs() > 1) {
5366 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5367 return;
5368 }
5369
5370 StringRef Str;
5371 SourceLocation ArgLoc;
5372
5373 if (AL.getNumArgs() == 0)
5374 Str = "";
5375 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5376 return;
5377
5378 ARMInterruptAttr::InterruptType Kind;
5379 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5380 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5381 << ArgLoc;
5382 return;
5383 }
5384
5385 unsigned Index = AL.getAttributeSpellingListIndex();
5386 D->addAttr(::new (S.Context)
5387 ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index));
5388 }
5389
handleMSP430InterruptAttr(Sema & S,Decl * D,const ParsedAttr & AL)5390 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5391 // MSP430 'interrupt' attribute is applied to
5392 // a function with no parameters and void return type.
5393 if (!isFunctionOrMethod(D)) {
5394 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5395 << "'interrupt'" << ExpectedFunctionOrMethod;
5396 return;
5397 }
5398
5399 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5400 S.Diag(D->getLocation(), diag::warn_msp430_interrupt_attribute)
5401 << 0;
5402 return;
5403 }
5404
5405 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5406 S.Diag(D->getLocation(), diag::warn_msp430_interrupt_attribute)
5407 << 1;
5408 return;
5409 }
5410
5411 // The attribute takes one integer argument.
5412 if (!checkAttributeNumArgs(S, AL, 1))
5413 return;
5414
5415 if (!AL.isArgExpr(0)) {
5416 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5417 << AL << AANT_ArgumentIntegerConstant;
5418 return;
5419 }
5420
5421 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5422 llvm::APSInt NumParams(32);
5423 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5424 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5425 << AL << AANT_ArgumentIntegerConstant
5426 << NumParamsExpr->getSourceRange();
5427 return;
5428 }
5429 // The argument should be in range 0..63.
5430 unsigned Num = NumParams.getLimitedValue(255);
5431 if (Num > 63) {
5432 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5433 << AL << (int)NumParams.getSExtValue()
5434 << NumParamsExpr->getSourceRange();
5435 return;
5436 }
5437
5438 D->addAttr(::new (S.Context)
5439 MSP430InterruptAttr(AL.getLoc(), S.Context, Num,
5440 AL.getAttributeSpellingListIndex()));
5441 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5442 }
5443
handleMipsInterruptAttr(Sema & S,Decl * D,const ParsedAttr & AL)5444 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5445 // Only one optional argument permitted.
5446 if (AL.getNumArgs() > 1) {
5447 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5448 return;
5449 }
5450
5451 StringRef Str;
5452 SourceLocation ArgLoc;
5453
5454 if (AL.getNumArgs() == 0)
5455 Str = "";
5456 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5457 return;
5458
5459 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5460 // a) Must be a function.
5461 // b) Must have no parameters.
5462 // c) Must have the 'void' return type.
5463 // d) Cannot have the 'mips16' attribute, as that instruction set
5464 // lacks the 'eret' instruction.
5465 // e) The attribute itself must either have no argument or one of the
5466 // valid interrupt types, see [MipsInterruptDocs].
5467
5468 if (!isFunctionOrMethod(D)) {
5469 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5470 << "'interrupt'" << ExpectedFunctionOrMethod;
5471 return;
5472 }
5473
5474 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5475 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5476 << 0;
5477 return;
5478 }
5479
5480 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5481 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5482 << 1;
5483 return;
5484 }
5485
5486 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
5487 return;
5488
5489 MipsInterruptAttr::InterruptType Kind;
5490 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5491 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5492 << AL << "'" + std::string(Str) + "'";
5493 return;
5494 }
5495
5496 D->addAttr(::new (S.Context) MipsInterruptAttr(
5497 AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
5498 }
5499
handleAnyX86InterruptAttr(Sema & S,Decl * D,const ParsedAttr & AL)5500 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5501 // Semantic checks for a function with the 'interrupt' attribute.
5502 // a) Must be a function.
5503 // b) Must have the 'void' return type.
5504 // c) Must take 1 or 2 arguments.
5505 // d) The 1st argument must be a pointer.
5506 // e) The 2nd argument (if any) must be an unsigned integer.
5507 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5508 CXXMethodDecl::isStaticOverloadedOperator(
5509 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5510 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5511 << AL << ExpectedFunctionWithProtoType;
5512 return;
5513 }
5514 // Interrupt handler must have void return type.
5515 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5516 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5517 diag::err_anyx86_interrupt_attribute)
5518 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5519 ? 0
5520 : 1)
5521 << 0;
5522 return;
5523 }
5524 // Interrupt handler must have 1 or 2 parameters.
5525 unsigned NumParams = getFunctionOrMethodNumParams(D);
5526 if (NumParams < 1 || NumParams > 2) {
5527 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
5528 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5529 ? 0
5530 : 1)
5531 << 1;
5532 return;
5533 }
5534 // The first argument must be a pointer.
5535 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5536 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5537 diag::err_anyx86_interrupt_attribute)
5538 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5539 ? 0
5540 : 1)
5541 << 2;
5542 return;
5543 }
5544 // The second argument, if present, must be an unsigned integer.
5545 unsigned TypeSize =
5546 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5547 ? 64
5548 : 32;
5549 if (NumParams == 2 &&
5550 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5551 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5552 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5553 diag::err_anyx86_interrupt_attribute)
5554 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5555 ? 0
5556 : 1)
5557 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5558 return;
5559 }
5560 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5561 AL.getLoc(), S.Context, AL.getAttributeSpellingListIndex()));
5562 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5563 }
5564
handleAVRInterruptAttr(Sema & S,Decl * D,const ParsedAttr & AL)5565 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5566 if (!isFunctionOrMethod(D)) {
5567 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5568 << "'interrupt'" << ExpectedFunction;
5569 return;
5570 }
5571
5572 if (!checkAttributeNumArgs(S, AL, 0))
5573 return;
5574
5575 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
5576 }
5577
handleAVRSignalAttr(Sema & S,Decl * D,const ParsedAttr & AL)5578 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5579 if (!isFunctionOrMethod(D)) {
5580 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5581 << "'signal'" << ExpectedFunction;
5582 return;
5583 }
5584
5585 if (!checkAttributeNumArgs(S, AL, 0))
5586 return;
5587
5588 handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
5589 }
5590
handleWebAssemblyImportModuleAttr(Sema & S,Decl * D,const ParsedAttr & AL)5591 static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5592 if (!isFunctionOrMethod(D)) {
5593 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5594 << "'import_module'" << ExpectedFunction;
5595 return;
5596 }
5597
5598 auto *FD = cast<FunctionDecl>(D);
5599 if (FD->isThisDeclarationADefinition()) {
5600 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5601 return;
5602 }
5603
5604 StringRef Str;
5605 SourceLocation ArgLoc;
5606 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5607 return;
5608
5609 FD->addAttr(::new (S.Context) WebAssemblyImportModuleAttr(
5610 AL.getRange(), S.Context, Str,
5611 AL.getAttributeSpellingListIndex()));
5612 }
5613
handleWebAssemblyImportNameAttr(Sema & S,Decl * D,const ParsedAttr & AL)5614 static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5615 if (!isFunctionOrMethod(D)) {
5616 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5617 << "'import_name'" << ExpectedFunction;
5618 return;
5619 }
5620
5621 auto *FD = cast<FunctionDecl>(D);
5622 if (FD->isThisDeclarationADefinition()) {
5623 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5624 return;
5625 }
5626
5627 StringRef Str;
5628 SourceLocation ArgLoc;
5629 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5630 return;
5631
5632 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(
5633 AL.getRange(), S.Context, Str,
5634 AL.getAttributeSpellingListIndex()));
5635 }
5636
handleRISCVInterruptAttr(Sema & S,Decl * D,const ParsedAttr & AL)5637 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
5638 const ParsedAttr &AL) {
5639 // Warn about repeated attributes.
5640 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
5641 S.Diag(AL.getRange().getBegin(),
5642 diag::warn_riscv_repeated_interrupt_attribute);
5643 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
5644 return;
5645 }
5646
5647 // Check the attribute argument. Argument is optional.
5648 if (!checkAttributeAtMostNumArgs(S, AL, 1))
5649 return;
5650
5651 StringRef Str;
5652 SourceLocation ArgLoc;
5653
5654 // 'machine'is the default interrupt mode.
5655 if (AL.getNumArgs() == 0)
5656 Str = "machine";
5657 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5658 return;
5659
5660 // Semantic checks for a function with the 'interrupt' attribute:
5661 // - Must be a function.
5662 // - Must have no parameters.
5663 // - Must have the 'void' return type.
5664 // - The attribute itself must either have no argument or one of the
5665 // valid interrupt types, see [RISCVInterruptDocs].
5666
5667 if (D->getFunctionType() == nullptr) {
5668 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5669 << "'interrupt'" << ExpectedFunction;
5670 return;
5671 }
5672
5673 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5674 S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 0;
5675 return;
5676 }
5677
5678 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5679 S.Diag(D->getLocation(), diag::warn_riscv_interrupt_attribute) << 1;
5680 return;
5681 }
5682
5683 RISCVInterruptAttr::InterruptType Kind;
5684 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5685 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5686 << ArgLoc;
5687 return;
5688 }
5689
5690 D->addAttr(::new (S.Context) RISCVInterruptAttr(
5691 AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
5692 }
5693
handleInterruptAttr(Sema & S,Decl * D,const ParsedAttr & AL)5694 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5695 // Dispatch the interrupt attribute based on the current target.
5696 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5697 case llvm::Triple::msp430:
5698 handleMSP430InterruptAttr(S, D, AL);
5699 break;
5700 case llvm::Triple::mipsel:
5701 case llvm::Triple::mips:
5702 handleMipsInterruptAttr(S, D, AL);
5703 break;
5704 case llvm::Triple::x86:
5705 case llvm::Triple::x86_64:
5706 handleAnyX86InterruptAttr(S, D, AL);
5707 break;
5708 case llvm::Triple::avr:
5709 handleAVRInterruptAttr(S, D, AL);
5710 break;
5711 case llvm::Triple::riscv32:
5712 case llvm::Triple::riscv64:
5713 handleRISCVInterruptAttr(S, D, AL);
5714 break;
5715 default:
5716 handleARMInterruptAttr(S, D, AL);
5717 break;
5718 }
5719 }
5720
handleAMDGPUFlatWorkGroupSizeAttr(Sema & S,Decl * D,const ParsedAttr & AL)5721 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5722 const ParsedAttr &AL) {
5723 uint32_t Min = 0;
5724 Expr *MinExpr = AL.getArgAsExpr(0);
5725 if (!checkUInt32Argument(S, AL, MinExpr, Min))
5726 return;
5727
5728 uint32_t Max = 0;
5729 Expr *MaxExpr = AL.getArgAsExpr(1);
5730 if (!checkUInt32Argument(S, AL, MaxExpr, Max))
5731 return;
5732
5733 if (Min == 0 && Max != 0) {
5734 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 0;
5735 return;
5736 }
5737 if (Min > Max) {
5738 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
5739 return;
5740 }
5741
5742 D->addAttr(::new (S.Context)
5743 AMDGPUFlatWorkGroupSizeAttr(AL.getLoc(), S.Context, Min, Max,
5744 AL.getAttributeSpellingListIndex()));
5745 }
5746
handleAMDGPUWavesPerEUAttr(Sema & S,Decl * D,const ParsedAttr & AL)5747 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5748 uint32_t Min = 0;
5749 Expr *MinExpr = AL.getArgAsExpr(0);
5750 if (!checkUInt32Argument(S, AL, MinExpr, Min))
5751 return;
5752
5753 uint32_t Max = 0;
5754 if (AL.getNumArgs() == 2) {
5755 Expr *MaxExpr = AL.getArgAsExpr(1);
5756 if (!checkUInt32Argument(S, AL, MaxExpr, Max))
5757 return;
5758 }
5759
5760 if (Min == 0 && Max != 0) {
5761 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 0;
5762 return;
5763 }
5764 if (Max != 0 && Min > Max) {
5765 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) << AL << 1;
5766 return;
5767 }
5768
5769 D->addAttr(::new (S.Context)
5770 AMDGPUWavesPerEUAttr(AL.getLoc(), S.Context, Min, Max,
5771 AL.getAttributeSpellingListIndex()));
5772 }
5773
handleAMDGPUNumSGPRAttr(Sema & S,Decl * D,const ParsedAttr & AL)5774 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5775 uint32_t NumSGPR = 0;
5776 Expr *NumSGPRExpr = AL.getArgAsExpr(0);
5777 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
5778 return;
5779
5780 D->addAttr(::new (S.Context)
5781 AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR,
5782 AL.getAttributeSpellingListIndex()));
5783 }
5784
handleAMDGPUNumVGPRAttr(Sema & S,Decl * D,const ParsedAttr & AL)5785 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5786 uint32_t NumVGPR = 0;
5787 Expr *NumVGPRExpr = AL.getArgAsExpr(0);
5788 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
5789 return;
5790
5791 D->addAttr(::new (S.Context)
5792 AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR,
5793 AL.getAttributeSpellingListIndex()));
5794 }
5795
handleX86ForceAlignArgPointerAttr(Sema & S,Decl * D,const ParsedAttr & AL)5796 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5797 const ParsedAttr &AL) {
5798 // If we try to apply it to a function pointer, don't warn, but don't
5799 // do anything, either. It doesn't matter anyway, because there's nothing
5800 // special about calling a force_align_arg_pointer function.
5801 const auto *VD = dyn_cast<ValueDecl>(D);
5802 if (VD && VD->getType()->isFunctionPointerType())
5803 return;
5804 // Also don't warn on function pointer typedefs.
5805 const auto *TD = dyn_cast<TypedefNameDecl>(D);
5806 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5807 TD->getUnderlyingType()->isFunctionType()))
5808 return;
5809 // Attribute can only be applied to function types.
5810 if (!isa<FunctionDecl>(D)) {
5811 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5812 << AL << ExpectedFunction;
5813 return;
5814 }
5815
5816 D->addAttr(::new (S.Context)
5817 X86ForceAlignArgPointerAttr(AL.getRange(), S.Context,
5818 AL.getAttributeSpellingListIndex()));
5819 }
5820
handleLayoutVersion(Sema & S,Decl * D,const ParsedAttr & AL)5821 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
5822 uint32_t Version;
5823 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5824 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
5825 return;
5826
5827 // TODO: Investigate what happens with the next major version of MSVC.
5828 if (Version != LangOptions::MSVC2015 / 100) {
5829 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5830 << AL << Version << VersionExpr->getSourceRange();
5831 return;
5832 }
5833
5834 // The attribute expects a "major" version number like 19, but new versions of
5835 // MSVC have moved to updating the "minor", or less significant numbers, so we
5836 // have to multiply by 100 now.
5837 Version *= 100;
5838
5839 D->addAttr(::new (S.Context)
5840 LayoutVersionAttr(AL.getRange(), S.Context, Version,
5841 AL.getAttributeSpellingListIndex()));
5842 }
5843
mergeDLLImportAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex)5844 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5845 unsigned AttrSpellingListIndex) {
5846 if (D->hasAttr<DLLExportAttr>()) {
5847 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5848 return nullptr;
5849 }
5850
5851 if (D->hasAttr<DLLImportAttr>())
5852 return nullptr;
5853
5854 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5855 }
5856
mergeDLLExportAttr(Decl * D,SourceRange Range,unsigned AttrSpellingListIndex)5857 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5858 unsigned AttrSpellingListIndex) {
5859 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5860 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5861 D->dropAttr<DLLImportAttr>();
5862 }
5863
5864 if (D->hasAttr<DLLExportAttr>())
5865 return nullptr;
5866
5867 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5868 }
5869
handleDLLAttr(Sema & S,Decl * D,const ParsedAttr & A)5870 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
5871 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5872 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5873 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
5874 return;
5875 }
5876
5877 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5878 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
5879 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5880 // MinGW doesn't allow dllimport on inline functions.
5881 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5882 << A;
5883 return;
5884 }
5885 }
5886
5887 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5888 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5889 MD->getParent()->isLambda()) {
5890 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
5891 return;
5892 }
5893 }
5894
5895 unsigned Index = A.getAttributeSpellingListIndex();
5896 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
5897 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5898 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5899 if (NewAttr)
5900 D->addAttr(NewAttr);
5901 }
5902
5903 MSInheritanceAttr *
mergeMSInheritanceAttr(Decl * D,SourceRange Range,bool BestCase,unsigned AttrSpellingListIndex,MSInheritanceAttr::Spelling SemanticSpelling)5904 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5905 unsigned AttrSpellingListIndex,
5906 MSInheritanceAttr::Spelling SemanticSpelling) {
5907 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5908 if (IA->getSemanticSpelling() == SemanticSpelling)
5909 return nullptr;
5910 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5911 << 1 /*previous declaration*/;
5912 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5913 D->dropAttr<MSInheritanceAttr>();
5914 }
5915
5916 auto *RD = cast<CXXRecordDecl>(D);
5917 if (RD->hasDefinition()) {
5918 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5919 SemanticSpelling)) {
5920 return nullptr;
5921 }
5922 } else {
5923 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5924 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5925 << 1 /*partial specialization*/;
5926 return nullptr;
5927 }
5928 if (RD->getDescribedClassTemplate()) {
5929 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5930 << 0 /*primary template*/;
5931 return nullptr;
5932 }
5933 }
5934
5935 return ::new (Context)
5936 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5937 }
5938
handleCapabilityAttr(Sema & S,Decl * D,const ParsedAttr & AL)5939 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5940 // The capability attributes take a single string parameter for the name of
5941 // the capability they represent. The lockable attribute does not take any
5942 // parameters. However, semantically, both attributes represent the same
5943 // concept, and so they use the same semantic attribute. Eventually, the
5944 // lockable attribute will be removed.
5945 //
5946 // For backward compatibility, any capability which has no specified string
5947 // literal will be considered a "mutex."
5948 StringRef N("mutex");
5949 SourceLocation LiteralLoc;
5950 if (AL.getKind() == ParsedAttr::AT_Capability &&
5951 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
5952 return;
5953
5954 // Currently, there are only two names allowed for a capability: role and
5955 // mutex (case insensitive). Diagnose other capability names.
5956 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5957 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5958
5959 D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N,
5960 AL.getAttributeSpellingListIndex()));
5961 }
5962
handleAssertCapabilityAttr(Sema & S,Decl * D,const ParsedAttr & AL)5963 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5964 SmallVector<Expr*, 1> Args;
5965 if (!checkLockFunAttrCommon(S, D, AL, Args))
5966 return;
5967
5968 D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context,
5969 Args.data(), Args.size(),
5970 AL.getAttributeSpellingListIndex()));
5971 }
5972
handleAcquireCapabilityAttr(Sema & S,Decl * D,const ParsedAttr & AL)5973 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5974 const ParsedAttr &AL) {
5975 SmallVector<Expr*, 1> Args;
5976 if (!checkLockFunAttrCommon(S, D, AL, Args))
5977 return;
5978
5979 D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(),
5980 S.Context,
5981 Args.data(), Args.size(),
5982 AL.getAttributeSpellingListIndex()));
5983 }
5984
handleTryAcquireCapabilityAttr(Sema & S,Decl * D,const ParsedAttr & AL)5985 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5986 const ParsedAttr &AL) {
5987 SmallVector<Expr*, 2> Args;
5988 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
5989 return;
5990
5991 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(),
5992 S.Context,
5993 AL.getArgAsExpr(0),
5994 Args.data(),
5995 Args.size(),
5996 AL.getAttributeSpellingListIndex()));
5997 }
5998
handleReleaseCapabilityAttr(Sema & S,Decl * D,const ParsedAttr & AL)5999 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
6000 const ParsedAttr &AL) {
6001 // Check that all arguments are lockable objects.
6002 SmallVector<Expr *, 1> Args;
6003 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
6004
6005 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
6006 AL.getRange(), S.Context, Args.data(), Args.size(),
6007 AL.getAttributeSpellingListIndex()));
6008 }
6009
handleRequiresCapabilityAttr(Sema & S,Decl * D,const ParsedAttr & AL)6010 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
6011 const ParsedAttr &AL) {
6012 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6013 return;
6014
6015 // check that all arguments are lockable objects
6016 SmallVector<Expr*, 1> Args;
6017 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
6018 if (Args.empty())
6019 return;
6020
6021 RequiresCapabilityAttr *RCA = ::new (S.Context)
6022 RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(),
6023 Args.size(), AL.getAttributeSpellingListIndex());
6024
6025 D->addAttr(RCA);
6026 }
6027
handleDeprecatedAttr(Sema & S,Decl * D,const ParsedAttr & AL)6028 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6029 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
6030 if (NSD->isAnonymousNamespace()) {
6031 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
6032 // Do not want to attach the attribute to the namespace because that will
6033 // cause confusing diagnostic reports for uses of declarations within the
6034 // namespace.
6035 return;
6036 }
6037 }
6038
6039 // Handle the cases where the attribute has a text message.
6040 StringRef Str, Replacement;
6041 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
6042 !S.checkStringLiteralArgumentAttr(AL, 0, Str))
6043 return;
6044
6045 // Only support a single optional message for Declspec and CXX11.
6046 if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
6047 checkAttributeAtMostNumArgs(S, AL, 1);
6048 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
6049 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
6050 return;
6051
6052 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
6053 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
6054
6055 D->addAttr(::new (S.Context)
6056 DeprecatedAttr(AL.getRange(), S.Context, Str, Replacement,
6057 AL.getAttributeSpellingListIndex()));
6058 }
6059
isGlobalVar(const Decl * D)6060 static bool isGlobalVar(const Decl *D) {
6061 if (const auto *S = dyn_cast<VarDecl>(D))
6062 return S->hasGlobalStorage();
6063 return false;
6064 }
6065
handleNoSanitizeAttr(Sema & S,Decl * D,const ParsedAttr & AL)6066 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6067 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6068 return;
6069
6070 std::vector<StringRef> Sanitizers;
6071
6072 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6073 StringRef SanitizerName;
6074 SourceLocation LiteralLoc;
6075
6076 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
6077 return;
6078
6079 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
6080 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
6081 else if (isGlobalVar(D) && SanitizerName != "address")
6082 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6083 << AL << ExpectedFunctionOrMethod;
6084 Sanitizers.push_back(SanitizerName);
6085 }
6086
6087 D->addAttr(::new (S.Context) NoSanitizeAttr(
6088 AL.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
6089 AL.getAttributeSpellingListIndex()));
6090 }
6091
handleNoSanitizeSpecificAttr(Sema & S,Decl * D,const ParsedAttr & AL)6092 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
6093 const ParsedAttr &AL) {
6094 StringRef AttrName = AL.getName()->getName();
6095 normalizeName(AttrName);
6096 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
6097 .Case("no_address_safety_analysis", "address")
6098 .Case("no_sanitize_address", "address")
6099 .Case("no_sanitize_thread", "thread")
6100 .Case("no_sanitize_memory", "memory");
6101 if (isGlobalVar(D) && SanitizerName != "address")
6102 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6103 << AL << ExpectedFunction;
6104 D->addAttr(::new (S.Context)
6105 NoSanitizeAttr(AL.getRange(), S.Context, &SanitizerName, 1,
6106 AL.getAttributeSpellingListIndex()));
6107 }
6108
handleInternalLinkageAttr(Sema & S,Decl * D,const ParsedAttr & AL)6109 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6110 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
6111 D->addAttr(Internal);
6112 }
6113
handleOpenCLNoSVMAttr(Sema & S,Decl * D,const ParsedAttr & AL)6114 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6115 if (S.LangOpts.OpenCLVersion != 200)
6116 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
6117 << AL << "2.0" << 0;
6118 else
6119 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
6120 << "2.0";
6121 }
6122
6123 /// Handles semantic checking for features that are common to all attributes,
6124 /// such as checking whether a parameter was properly specified, or the correct
6125 /// number of arguments were passed, etc.
handleCommonAttributeFeatures(Sema & S,Decl * D,const ParsedAttr & AL)6126 static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
6127 const ParsedAttr &AL) {
6128 // Several attributes carry different semantics than the parsing requires, so
6129 // those are opted out of the common argument checks.
6130 //
6131 // We also bail on unknown and ignored attributes because those are handled
6132 // as part of the target-specific handling logic.
6133 if (AL.getKind() == ParsedAttr::UnknownAttribute)
6134 return false;
6135 // Check whether the attribute requires specific language extensions to be
6136 // enabled.
6137 if (!AL.diagnoseLangOpts(S))
6138 return true;
6139 // Check whether the attribute appertains to the given subject.
6140 if (!AL.diagnoseAppertainsTo(S, D))
6141 return true;
6142 if (AL.hasCustomParsing())
6143 return false;
6144
6145 if (AL.getMinArgs() == AL.getMaxArgs()) {
6146 // If there are no optional arguments, then checking for the argument count
6147 // is trivial.
6148 if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
6149 return true;
6150 } else {
6151 // There are optional arguments, so checking is slightly more involved.
6152 if (AL.getMinArgs() &&
6153 !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
6154 return true;
6155 else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
6156 !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
6157 return true;
6158 }
6159
6160 if (S.CheckAttrTarget(AL))
6161 return true;
6162
6163 return false;
6164 }
6165
handleOpenCLAccessAttr(Sema & S,Decl * D,const ParsedAttr & AL)6166 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6167 if (D->isInvalidDecl())
6168 return;
6169
6170 // Check if there is only one access qualifier.
6171 if (D->hasAttr<OpenCLAccessAttr>()) {
6172 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
6173 AL.getSemanticSpelling()) {
6174 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
6175 << AL.getName()->getName() << AL.getRange();
6176 } else {
6177 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
6178 << D->getSourceRange();
6179 D->setInvalidDecl(true);
6180 return;
6181 }
6182 }
6183
6184 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
6185 // image object can be read and written.
6186 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
6187 // object. Using the read_write (or __read_write) qualifier with the pipe
6188 // qualifier is a compilation error.
6189 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
6190 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
6191 if (AL.getName()->getName().find("read_write") != StringRef::npos) {
6192 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
6193 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
6194 << AL << PDecl->getType() << DeclTy->isImageType();
6195 D->setInvalidDecl(true);
6196 return;
6197 }
6198 }
6199 }
6200
6201 D->addAttr(::new (S.Context) OpenCLAccessAttr(
6202 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
6203 }
6204
handleDestroyAttr(Sema & S,Decl * D,const ParsedAttr & A)6205 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6206 if (!cast<VarDecl>(D)->hasGlobalStorage()) {
6207 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
6208 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
6209 return;
6210 }
6211
6212 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
6213 handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
6214 else
6215 handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
6216 }
6217
handleUninitializedAttr(Sema & S,Decl * D,const ParsedAttr & AL)6218 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6219 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
6220 "uninitialized is only valid on automatic duration variables");
6221 unsigned Index = AL.getAttributeSpellingListIndex();
6222 D->addAttr(::new (S.Context)
6223 UninitializedAttr(AL.getLoc(), S.Context, Index));
6224 }
6225
tryMakeVariablePseudoStrong(Sema & S,VarDecl * VD,bool DiagnoseFailure)6226 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
6227 bool DiagnoseFailure) {
6228 QualType Ty = VD->getType();
6229 if (!Ty->isObjCRetainableType()) {
6230 if (DiagnoseFailure) {
6231 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6232 << 0;
6233 }
6234 return false;
6235 }
6236
6237 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
6238
6239 // Sema::inferObjCARCLifetime must run after processing decl attributes
6240 // (because __block lowers to an attribute), so if the lifetime hasn't been
6241 // explicitly specified, infer it locally now.
6242 if (LifetimeQual == Qualifiers::OCL_None)
6243 LifetimeQual = Ty->getObjCARCImplicitLifetime();
6244
6245 // The attributes only really makes sense for __strong variables; ignore any
6246 // attempts to annotate a parameter with any other lifetime qualifier.
6247 if (LifetimeQual != Qualifiers::OCL_Strong) {
6248 if (DiagnoseFailure) {
6249 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6250 << 1;
6251 }
6252 return false;
6253 }
6254
6255 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
6256 // to ensure that the variable is 'const' so that we can error on
6257 // modification, which can otherwise over-release.
6258 VD->setType(Ty.withConst());
6259 VD->setARCPseudoStrong(true);
6260 return true;
6261 }
6262
handleObjCExternallyRetainedAttr(Sema & S,Decl * D,const ParsedAttr & AL)6263 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
6264 const ParsedAttr &AL) {
6265 if (auto *VD = dyn_cast<VarDecl>(D)) {
6266 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
6267 if (!VD->hasLocalStorage()) {
6268 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6269 << 0;
6270 return;
6271 }
6272
6273 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
6274 return;
6275
6276 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6277 return;
6278 }
6279
6280 // If D is a function-like declaration (method, block, or function), then we
6281 // make every parameter psuedo-strong.
6282 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
6283 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
6284 QualType Ty = PVD->getType();
6285
6286 // If a user wrote a parameter with __strong explicitly, then assume they
6287 // want "real" strong semantics for that parameter. This works because if
6288 // the parameter was written with __strong, then the strong qualifier will
6289 // be non-local.
6290 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
6291 Qualifiers::OCL_Strong)
6292 continue;
6293
6294 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
6295 }
6296 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6297 }
6298
6299 //===----------------------------------------------------------------------===//
6300 // Top Level Sema Entry Points
6301 //===----------------------------------------------------------------------===//
6302
6303 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
6304 /// the attribute applies to decls. If the attribute is a type attribute, just
6305 /// silently ignore it if a GNU attribute.
ProcessDeclAttribute(Sema & S,Scope * scope,Decl * D,const ParsedAttr & AL,bool IncludeCXX11Attributes)6306 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
6307 const ParsedAttr &AL,
6308 bool IncludeCXX11Attributes) {
6309 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
6310 return;
6311
6312 // Ignore C++11 attributes on declarator chunks: they appertain to the type
6313 // instead.
6314 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
6315 return;
6316
6317 // Unknown attributes are automatically warned on. Target-specific attributes
6318 // which do not apply to the current target architecture are treated as
6319 // though they were unknown attributes.
6320 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
6321 !AL.existsInTarget(S.Context.getTargetInfo())) {
6322 S.Diag(AL.getLoc(),
6323 AL.isDeclspecAttribute()
6324 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
6325 : (unsigned)diag::warn_unknown_attribute_ignored)
6326 << AL;
6327 return;
6328 }
6329
6330 if (handleCommonAttributeFeatures(S, D, AL))
6331 return;
6332
6333 switch (AL.getKind()) {
6334 default:
6335 if (!AL.isStmtAttr()) {
6336 // Type attributes are handled elsewhere; silently move on.
6337 assert(AL.isTypeAttr() && "Non-type attribute not handled");
6338 break;
6339 }
6340 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
6341 << AL << D->getLocation();
6342 break;
6343 case ParsedAttr::AT_Interrupt:
6344 handleInterruptAttr(S, D, AL);
6345 break;
6346 case ParsedAttr::AT_X86ForceAlignArgPointer:
6347 handleX86ForceAlignArgPointerAttr(S, D, AL);
6348 break;
6349 case ParsedAttr::AT_DLLExport:
6350 case ParsedAttr::AT_DLLImport:
6351 handleDLLAttr(S, D, AL);
6352 break;
6353 case ParsedAttr::AT_Mips16:
6354 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6355 MipsInterruptAttr>(S, D, AL);
6356 break;
6357 case ParsedAttr::AT_NoMips16:
6358 handleSimpleAttribute<NoMips16Attr>(S, D, AL);
6359 break;
6360 case ParsedAttr::AT_MicroMips:
6361 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
6362 break;
6363 case ParsedAttr::AT_NoMicroMips:
6364 handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL);
6365 break;
6366 case ParsedAttr::AT_MipsLongCall:
6367 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6368 S, D, AL);
6369 break;
6370 case ParsedAttr::AT_MipsShortCall:
6371 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6372 S, D, AL);
6373 break;
6374 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
6375 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
6376 break;
6377 case ParsedAttr::AT_AMDGPUWavesPerEU:
6378 handleAMDGPUWavesPerEUAttr(S, D, AL);
6379 break;
6380 case ParsedAttr::AT_AMDGPUNumSGPR:
6381 handleAMDGPUNumSGPRAttr(S, D, AL);
6382 break;
6383 case ParsedAttr::AT_AMDGPUNumVGPR:
6384 handleAMDGPUNumVGPRAttr(S, D, AL);
6385 break;
6386 case ParsedAttr::AT_AVRSignal:
6387 handleAVRSignalAttr(S, D, AL);
6388 break;
6389 case ParsedAttr::AT_WebAssemblyImportModule:
6390 handleWebAssemblyImportModuleAttr(S, D, AL);
6391 break;
6392 case ParsedAttr::AT_WebAssemblyImportName:
6393 handleWebAssemblyImportNameAttr(S, D, AL);
6394 break;
6395 case ParsedAttr::AT_IBAction:
6396 handleSimpleAttribute<IBActionAttr>(S, D, AL);
6397 break;
6398 case ParsedAttr::AT_IBOutlet:
6399 handleIBOutlet(S, D, AL);
6400 break;
6401 case ParsedAttr::AT_IBOutletCollection:
6402 handleIBOutletCollection(S, D, AL);
6403 break;
6404 case ParsedAttr::AT_IFunc:
6405 handleIFuncAttr(S, D, AL);
6406 break;
6407 case ParsedAttr::AT_Alias:
6408 handleAliasAttr(S, D, AL);
6409 break;
6410 case ParsedAttr::AT_Aligned:
6411 handleAlignedAttr(S, D, AL);
6412 break;
6413 case ParsedAttr::AT_AlignValue:
6414 handleAlignValueAttr(S, D, AL);
6415 break;
6416 case ParsedAttr::AT_AllocSize:
6417 handleAllocSizeAttr(S, D, AL);
6418 break;
6419 case ParsedAttr::AT_AlwaysInline:
6420 handleAlwaysInlineAttr(S, D, AL);
6421 break;
6422 case ParsedAttr::AT_Artificial:
6423 handleSimpleAttribute<ArtificialAttr>(S, D, AL);
6424 break;
6425 case ParsedAttr::AT_AnalyzerNoReturn:
6426 handleAnalyzerNoReturnAttr(S, D, AL);
6427 break;
6428 case ParsedAttr::AT_TLSModel:
6429 handleTLSModelAttr(S, D, AL);
6430 break;
6431 case ParsedAttr::AT_Annotate:
6432 handleAnnotateAttr(S, D, AL);
6433 break;
6434 case ParsedAttr::AT_Availability:
6435 handleAvailabilityAttr(S, D, AL);
6436 break;
6437 case ParsedAttr::AT_CarriesDependency:
6438 handleDependencyAttr(S, scope, D, AL);
6439 break;
6440 case ParsedAttr::AT_CPUDispatch:
6441 case ParsedAttr::AT_CPUSpecific:
6442 handleCPUSpecificAttr(S, D, AL);
6443 break;
6444 case ParsedAttr::AT_Common:
6445 handleCommonAttr(S, D, AL);
6446 break;
6447 case ParsedAttr::AT_CUDAConstant:
6448 handleConstantAttr(S, D, AL);
6449 break;
6450 case ParsedAttr::AT_PassObjectSize:
6451 handlePassObjectSizeAttr(S, D, AL);
6452 break;
6453 case ParsedAttr::AT_Constructor:
6454 handleConstructorAttr(S, D, AL);
6455 break;
6456 case ParsedAttr::AT_CXX11NoReturn:
6457 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL);
6458 break;
6459 case ParsedAttr::AT_Deprecated:
6460 handleDeprecatedAttr(S, D, AL);
6461 break;
6462 case ParsedAttr::AT_Destructor:
6463 handleDestructorAttr(S, D, AL);
6464 break;
6465 case ParsedAttr::AT_EnableIf:
6466 handleEnableIfAttr(S, D, AL);
6467 break;
6468 case ParsedAttr::AT_DiagnoseIf:
6469 handleDiagnoseIfAttr(S, D, AL);
6470 break;
6471 case ParsedAttr::AT_ExtVectorType:
6472 handleExtVectorTypeAttr(S, D, AL);
6473 break;
6474 case ParsedAttr::AT_ExternalSourceSymbol:
6475 handleExternalSourceSymbolAttr(S, D, AL);
6476 break;
6477 case ParsedAttr::AT_MinSize:
6478 handleMinSizeAttr(S, D, AL);
6479 break;
6480 case ParsedAttr::AT_OptimizeNone:
6481 handleOptimizeNoneAttr(S, D, AL);
6482 break;
6483 case ParsedAttr::AT_FlagEnum:
6484 handleSimpleAttribute<FlagEnumAttr>(S, D, AL);
6485 break;
6486 case ParsedAttr::AT_EnumExtensibility:
6487 handleEnumExtensibilityAttr(S, D, AL);
6488 break;
6489 case ParsedAttr::AT_Flatten:
6490 handleSimpleAttribute<FlattenAttr>(S, D, AL);
6491 break;
6492 case ParsedAttr::AT_Format:
6493 handleFormatAttr(S, D, AL);
6494 break;
6495 case ParsedAttr::AT_FormatArg:
6496 handleFormatArgAttr(S, D, AL);
6497 break;
6498 case ParsedAttr::AT_CUDAGlobal:
6499 handleGlobalAttr(S, D, AL);
6500 break;
6501 case ParsedAttr::AT_CUDADevice:
6502 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6503 AL);
6504 break;
6505 case ParsedAttr::AT_CUDAHost:
6506 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
6507 break;
6508 case ParsedAttr::AT_GNUInline:
6509 handleGNUInlineAttr(S, D, AL);
6510 break;
6511 case ParsedAttr::AT_CUDALaunchBounds:
6512 handleLaunchBoundsAttr(S, D, AL);
6513 break;
6514 case ParsedAttr::AT_Restrict:
6515 handleRestrictAttr(S, D, AL);
6516 break;
6517 case ParsedAttr::AT_LifetimeBound:
6518 handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL);
6519 break;
6520 case ParsedAttr::AT_MayAlias:
6521 handleSimpleAttribute<MayAliasAttr>(S, D, AL);
6522 break;
6523 case ParsedAttr::AT_Mode:
6524 handleModeAttr(S, D, AL);
6525 break;
6526 case ParsedAttr::AT_NoAlias:
6527 handleSimpleAttribute<NoAliasAttr>(S, D, AL);
6528 break;
6529 case ParsedAttr::AT_NoCommon:
6530 handleSimpleAttribute<NoCommonAttr>(S, D, AL);
6531 break;
6532 case ParsedAttr::AT_NoSplitStack:
6533 handleSimpleAttribute<NoSplitStackAttr>(S, D, AL);
6534 break;
6535 case ParsedAttr::AT_NonNull:
6536 if (auto *PVD = dyn_cast<ParmVarDecl>(D))
6537 handleNonNullAttrParameter(S, PVD, AL);
6538 else
6539 handleNonNullAttr(S, D, AL);
6540 break;
6541 case ParsedAttr::AT_ReturnsNonNull:
6542 handleReturnsNonNullAttr(S, D, AL);
6543 break;
6544 case ParsedAttr::AT_NoEscape:
6545 handleNoEscapeAttr(S, D, AL);
6546 break;
6547 case ParsedAttr::AT_AssumeAligned:
6548 handleAssumeAlignedAttr(S, D, AL);
6549 break;
6550 case ParsedAttr::AT_AllocAlign:
6551 handleAllocAlignAttr(S, D, AL);
6552 break;
6553 case ParsedAttr::AT_Overloadable:
6554 handleSimpleAttribute<OverloadableAttr>(S, D, AL);
6555 break;
6556 case ParsedAttr::AT_Ownership:
6557 handleOwnershipAttr(S, D, AL);
6558 break;
6559 case ParsedAttr::AT_Cold:
6560 handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
6561 break;
6562 case ParsedAttr::AT_Hot:
6563 handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
6564 break;
6565 case ParsedAttr::AT_Naked:
6566 handleNakedAttr(S, D, AL);
6567 break;
6568 case ParsedAttr::AT_NoReturn:
6569 handleNoReturnAttr(S, D, AL);
6570 break;
6571 case ParsedAttr::AT_AnyX86NoCfCheck:
6572 handleNoCfCheckAttr(S, D, AL);
6573 break;
6574 case ParsedAttr::AT_NoThrow:
6575 handleSimpleAttribute<NoThrowAttr>(S, D, AL);
6576 break;
6577 case ParsedAttr::AT_CUDAShared:
6578 handleSharedAttr(S, D, AL);
6579 break;
6580 case ParsedAttr::AT_VecReturn:
6581 handleVecReturnAttr(S, D, AL);
6582 break;
6583 case ParsedAttr::AT_ObjCOwnership:
6584 handleObjCOwnershipAttr(S, D, AL);
6585 break;
6586 case ParsedAttr::AT_ObjCPreciseLifetime:
6587 handleObjCPreciseLifetimeAttr(S, D, AL);
6588 break;
6589 case ParsedAttr::AT_ObjCReturnsInnerPointer:
6590 handleObjCReturnsInnerPointerAttr(S, D, AL);
6591 break;
6592 case ParsedAttr::AT_ObjCRequiresSuper:
6593 handleObjCRequiresSuperAttr(S, D, AL);
6594 break;
6595 case ParsedAttr::AT_ObjCBridge:
6596 handleObjCBridgeAttr(S, D, AL);
6597 break;
6598 case ParsedAttr::AT_ObjCBridgeMutable:
6599 handleObjCBridgeMutableAttr(S, D, AL);
6600 break;
6601 case ParsedAttr::AT_ObjCBridgeRelated:
6602 handleObjCBridgeRelatedAttr(S, D, AL);
6603 break;
6604 case ParsedAttr::AT_ObjCDesignatedInitializer:
6605 handleObjCDesignatedInitializer(S, D, AL);
6606 break;
6607 case ParsedAttr::AT_ObjCRuntimeName:
6608 handleObjCRuntimeName(S, D, AL);
6609 break;
6610 case ParsedAttr::AT_ObjCRuntimeVisible:
6611 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL);
6612 break;
6613 case ParsedAttr::AT_ObjCBoxable:
6614 handleObjCBoxable(S, D, AL);
6615 break;
6616 case ParsedAttr::AT_CFAuditedTransfer:
6617 handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
6618 CFUnknownTransferAttr>(S, D, AL);
6619 break;
6620 case ParsedAttr::AT_CFUnknownTransfer:
6621 handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
6622 CFAuditedTransferAttr>(S, D, AL);
6623 break;
6624 case ParsedAttr::AT_CFConsumed:
6625 case ParsedAttr::AT_NSConsumed:
6626 case ParsedAttr::AT_OSConsumed:
6627 S.AddXConsumedAttr(D, AL.getRange(), AL.getAttributeSpellingListIndex(),
6628 parsedAttrToRetainOwnershipKind(AL),
6629 /*IsTemplateInstantiation=*/false);
6630 break;
6631 case ParsedAttr::AT_NSConsumesSelf:
6632 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL);
6633 break;
6634 case ParsedAttr::AT_OSConsumesThis:
6635 handleSimpleAttribute<OSConsumesThisAttr>(S, D, AL);
6636 break;
6637 case ParsedAttr::AT_OSReturnsRetainedOnZero:
6638 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
6639 S, D, AL, isValidOSObjectOutParameter(D),
6640 diag::warn_ns_attribute_wrong_parameter_type,
6641 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
6642 break;
6643 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
6644 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
6645 S, D, AL, isValidOSObjectOutParameter(D),
6646 diag::warn_ns_attribute_wrong_parameter_type,
6647 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
6648 break;
6649 case ParsedAttr::AT_NSReturnsAutoreleased:
6650 case ParsedAttr::AT_NSReturnsNotRetained:
6651 case ParsedAttr::AT_NSReturnsRetained:
6652 case ParsedAttr::AT_CFReturnsNotRetained:
6653 case ParsedAttr::AT_CFReturnsRetained:
6654 case ParsedAttr::AT_OSReturnsNotRetained:
6655 case ParsedAttr::AT_OSReturnsRetained:
6656 handleXReturnsXRetainedAttr(S, D, AL);
6657 break;
6658 case ParsedAttr::AT_WorkGroupSizeHint:
6659 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
6660 break;
6661 case ParsedAttr::AT_ReqdWorkGroupSize:
6662 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
6663 break;
6664 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
6665 handleSubGroupSize(S, D, AL);
6666 break;
6667 case ParsedAttr::AT_VecTypeHint:
6668 handleVecTypeHint(S, D, AL);
6669 break;
6670 case ParsedAttr::AT_RequireConstantInit:
6671 handleSimpleAttribute<RequireConstantInitAttr>(S, D, AL);
6672 break;
6673 case ParsedAttr::AT_InitPriority:
6674 handleInitPriorityAttr(S, D, AL);
6675 break;
6676 case ParsedAttr::AT_Packed:
6677 handlePackedAttr(S, D, AL);
6678 break;
6679 case ParsedAttr::AT_Section:
6680 handleSectionAttr(S, D, AL);
6681 break;
6682 case ParsedAttr::AT_SpeculativeLoadHardening:
6683 handleSimpleAttribute<SpeculativeLoadHardeningAttr>(S, D, AL);
6684 break;
6685 case ParsedAttr::AT_CodeSeg:
6686 handleCodeSegAttr(S, D, AL);
6687 break;
6688 case ParsedAttr::AT_Target:
6689 handleTargetAttr(S, D, AL);
6690 break;
6691 case ParsedAttr::AT_MinVectorWidth:
6692 handleMinVectorWidthAttr(S, D, AL);
6693 break;
6694 case ParsedAttr::AT_Unavailable:
6695 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
6696 break;
6697 case ParsedAttr::AT_ArcWeakrefUnavailable:
6698 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL);
6699 break;
6700 case ParsedAttr::AT_ObjCRootClass:
6701 handleSimpleAttribute<ObjCRootClassAttr>(S, D, AL);
6702 break;
6703 case ParsedAttr::AT_ObjCSubclassingRestricted:
6704 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL);
6705 break;
6706 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
6707 handleObjCSuppresProtocolAttr(S, D, AL);
6708 break;
6709 case ParsedAttr::AT_ObjCRequiresPropertyDefs:
6710 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL);
6711 break;
6712 case ParsedAttr::AT_Unused:
6713 handleUnusedAttr(S, D, AL);
6714 break;
6715 case ParsedAttr::AT_ReturnsTwice:
6716 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL);
6717 break;
6718 case ParsedAttr::AT_NotTailCalled:
6719 handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
6720 S, D, AL);
6721 break;
6722 case ParsedAttr::AT_DisableTailCalls:
6723 handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
6724 AL);
6725 break;
6726 case ParsedAttr::AT_Used:
6727 handleSimpleAttribute<UsedAttr>(S, D, AL);
6728 break;
6729 case ParsedAttr::AT_Visibility:
6730 handleVisibilityAttr(S, D, AL, false);
6731 break;
6732 case ParsedAttr::AT_TypeVisibility:
6733 handleVisibilityAttr(S, D, AL, true);
6734 break;
6735 case ParsedAttr::AT_WarnUnused:
6736 handleSimpleAttribute<WarnUnusedAttr>(S, D, AL);
6737 break;
6738 case ParsedAttr::AT_WarnUnusedResult:
6739 handleWarnUnusedResult(S, D, AL);
6740 break;
6741 case ParsedAttr::AT_Weak:
6742 handleSimpleAttribute<WeakAttr>(S, D, AL);
6743 break;
6744 case ParsedAttr::AT_WeakRef:
6745 handleWeakRefAttr(S, D, AL);
6746 break;
6747 case ParsedAttr::AT_WeakImport:
6748 handleWeakImportAttr(S, D, AL);
6749 break;
6750 case ParsedAttr::AT_TransparentUnion:
6751 handleTransparentUnionAttr(S, D, AL);
6752 break;
6753 case ParsedAttr::AT_ObjCException:
6754 handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL);
6755 break;
6756 case ParsedAttr::AT_ObjCMethodFamily:
6757 handleObjCMethodFamilyAttr(S, D, AL);
6758 break;
6759 case ParsedAttr::AT_ObjCNSObject:
6760 handleObjCNSObject(S, D, AL);
6761 break;
6762 case ParsedAttr::AT_ObjCIndependentClass:
6763 handleObjCIndependentClass(S, D, AL);
6764 break;
6765 case ParsedAttr::AT_Blocks:
6766 handleBlocksAttr(S, D, AL);
6767 break;
6768 case ParsedAttr::AT_Sentinel:
6769 handleSentinelAttr(S, D, AL);
6770 break;
6771 case ParsedAttr::AT_Const:
6772 handleSimpleAttribute<ConstAttr>(S, D, AL);
6773 break;
6774 case ParsedAttr::AT_Pure:
6775 handleSimpleAttribute<PureAttr>(S, D, AL);
6776 break;
6777 case ParsedAttr::AT_Cleanup:
6778 handleCleanupAttr(S, D, AL);
6779 break;
6780 case ParsedAttr::AT_NoDebug:
6781 handleNoDebugAttr(S, D, AL);
6782 break;
6783 case ParsedAttr::AT_NoDuplicate:
6784 handleSimpleAttribute<NoDuplicateAttr>(S, D, AL);
6785 break;
6786 case ParsedAttr::AT_Convergent:
6787 handleSimpleAttribute<ConvergentAttr>(S, D, AL);
6788 break;
6789 case ParsedAttr::AT_NoInline:
6790 handleSimpleAttribute<NoInlineAttr>(S, D, AL);
6791 break;
6792 case ParsedAttr::AT_NoInstrumentFunction: // Interacts with -pg.
6793 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, AL);
6794 break;
6795 case ParsedAttr::AT_NoStackProtector:
6796 // Interacts with -fstack-protector options.
6797 handleSimpleAttribute<NoStackProtectorAttr>(S, D, AL);
6798 break;
6799 case ParsedAttr::AT_StdCall:
6800 case ParsedAttr::AT_CDecl:
6801 case ParsedAttr::AT_FastCall:
6802 case ParsedAttr::AT_ThisCall:
6803 case ParsedAttr::AT_Pascal:
6804 case ParsedAttr::AT_RegCall:
6805 case ParsedAttr::AT_SwiftCall:
6806 case ParsedAttr::AT_VectorCall:
6807 case ParsedAttr::AT_MSABI:
6808 case ParsedAttr::AT_SysVABI:
6809 case ParsedAttr::AT_Pcs:
6810 case ParsedAttr::AT_IntelOclBicc:
6811 case ParsedAttr::AT_PreserveMost:
6812 case ParsedAttr::AT_PreserveAll:
6813 case ParsedAttr::AT_AArch64VectorPcs:
6814 handleCallConvAttr(S, D, AL);
6815 break;
6816 case ParsedAttr::AT_Suppress:
6817 handleSuppressAttr(S, D, AL);
6818 break;
6819 case ParsedAttr::AT_OpenCLKernel:
6820 handleSimpleAttribute<OpenCLKernelAttr>(S, D, AL);
6821 break;
6822 case ParsedAttr::AT_OpenCLAccess:
6823 handleOpenCLAccessAttr(S, D, AL);
6824 break;
6825 case ParsedAttr::AT_OpenCLNoSVM:
6826 handleOpenCLNoSVMAttr(S, D, AL);
6827 break;
6828 case ParsedAttr::AT_SwiftContext:
6829 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftContext);
6830 break;
6831 case ParsedAttr::AT_SwiftErrorResult:
6832 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftErrorResult);
6833 break;
6834 case ParsedAttr::AT_SwiftIndirectResult:
6835 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftIndirectResult);
6836 break;
6837 case ParsedAttr::AT_InternalLinkage:
6838 handleInternalLinkageAttr(S, D, AL);
6839 break;
6840 case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
6841 handleSimpleAttribute<ExcludeFromExplicitInstantiationAttr>(S, D, AL);
6842 break;
6843 case ParsedAttr::AT_LTOVisibilityPublic:
6844 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, AL);
6845 break;
6846
6847 // Microsoft attributes:
6848 case ParsedAttr::AT_EmptyBases:
6849 handleSimpleAttribute<EmptyBasesAttr>(S, D, AL);
6850 break;
6851 case ParsedAttr::AT_LayoutVersion:
6852 handleLayoutVersion(S, D, AL);
6853 break;
6854 case ParsedAttr::AT_TrivialABI:
6855 handleSimpleAttribute<TrivialABIAttr>(S, D, AL);
6856 break;
6857 case ParsedAttr::AT_MSNoVTable:
6858 handleSimpleAttribute<MSNoVTableAttr>(S, D, AL);
6859 break;
6860 case ParsedAttr::AT_MSStruct:
6861 handleSimpleAttribute<MSStructAttr>(S, D, AL);
6862 break;
6863 case ParsedAttr::AT_Uuid:
6864 handleUuidAttr(S, D, AL);
6865 break;
6866 case ParsedAttr::AT_MSInheritance:
6867 handleMSInheritanceAttr(S, D, AL);
6868 break;
6869 case ParsedAttr::AT_SelectAny:
6870 handleSimpleAttribute<SelectAnyAttr>(S, D, AL);
6871 break;
6872 case ParsedAttr::AT_Thread:
6873 handleDeclspecThreadAttr(S, D, AL);
6874 break;
6875
6876 case ParsedAttr::AT_AbiTag:
6877 handleAbiTagAttr(S, D, AL);
6878 break;
6879
6880 // Thread safety attributes:
6881 case ParsedAttr::AT_AssertExclusiveLock:
6882 handleAssertExclusiveLockAttr(S, D, AL);
6883 break;
6884 case ParsedAttr::AT_AssertSharedLock:
6885 handleAssertSharedLockAttr(S, D, AL);
6886 break;
6887 case ParsedAttr::AT_GuardedVar:
6888 handleSimpleAttribute<GuardedVarAttr>(S, D, AL);
6889 break;
6890 case ParsedAttr::AT_PtGuardedVar:
6891 handlePtGuardedVarAttr(S, D, AL);
6892 break;
6893 case ParsedAttr::AT_ScopedLockable:
6894 handleSimpleAttribute<ScopedLockableAttr>(S, D, AL);
6895 break;
6896 case ParsedAttr::AT_NoSanitize:
6897 handleNoSanitizeAttr(S, D, AL);
6898 break;
6899 case ParsedAttr::AT_NoSanitizeSpecific:
6900 handleNoSanitizeSpecificAttr(S, D, AL);
6901 break;
6902 case ParsedAttr::AT_NoThreadSafetyAnalysis:
6903 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, AL);
6904 break;
6905 case ParsedAttr::AT_GuardedBy:
6906 handleGuardedByAttr(S, D, AL);
6907 break;
6908 case ParsedAttr::AT_PtGuardedBy:
6909 handlePtGuardedByAttr(S, D, AL);
6910 break;
6911 case ParsedAttr::AT_ExclusiveTrylockFunction:
6912 handleExclusiveTrylockFunctionAttr(S, D, AL);
6913 break;
6914 case ParsedAttr::AT_LockReturned:
6915 handleLockReturnedAttr(S, D, AL);
6916 break;
6917 case ParsedAttr::AT_LocksExcluded:
6918 handleLocksExcludedAttr(S, D, AL);
6919 break;
6920 case ParsedAttr::AT_SharedTrylockFunction:
6921 handleSharedTrylockFunctionAttr(S, D, AL);
6922 break;
6923 case ParsedAttr::AT_AcquiredBefore:
6924 handleAcquiredBeforeAttr(S, D, AL);
6925 break;
6926 case ParsedAttr::AT_AcquiredAfter:
6927 handleAcquiredAfterAttr(S, D, AL);
6928 break;
6929
6930 // Capability analysis attributes.
6931 case ParsedAttr::AT_Capability:
6932 case ParsedAttr::AT_Lockable:
6933 handleCapabilityAttr(S, D, AL);
6934 break;
6935 case ParsedAttr::AT_RequiresCapability:
6936 handleRequiresCapabilityAttr(S, D, AL);
6937 break;
6938
6939 case ParsedAttr::AT_AssertCapability:
6940 handleAssertCapabilityAttr(S, D, AL);
6941 break;
6942 case ParsedAttr::AT_AcquireCapability:
6943 handleAcquireCapabilityAttr(S, D, AL);
6944 break;
6945 case ParsedAttr::AT_ReleaseCapability:
6946 handleReleaseCapabilityAttr(S, D, AL);
6947 break;
6948 case ParsedAttr::AT_TryAcquireCapability:
6949 handleTryAcquireCapabilityAttr(S, D, AL);
6950 break;
6951
6952 // Consumed analysis attributes.
6953 case ParsedAttr::AT_Consumable:
6954 handleConsumableAttr(S, D, AL);
6955 break;
6956 case ParsedAttr::AT_ConsumableAutoCast:
6957 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, AL);
6958 break;
6959 case ParsedAttr::AT_ConsumableSetOnRead:
6960 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, AL);
6961 break;
6962 case ParsedAttr::AT_CallableWhen:
6963 handleCallableWhenAttr(S, D, AL);
6964 break;
6965 case ParsedAttr::AT_ParamTypestate:
6966 handleParamTypestateAttr(S, D, AL);
6967 break;
6968 case ParsedAttr::AT_ReturnTypestate:
6969 handleReturnTypestateAttr(S, D, AL);
6970 break;
6971 case ParsedAttr::AT_SetTypestate:
6972 handleSetTypestateAttr(S, D, AL);
6973 break;
6974 case ParsedAttr::AT_TestTypestate:
6975 handleTestTypestateAttr(S, D, AL);
6976 break;
6977
6978 // Type safety attributes.
6979 case ParsedAttr::AT_ArgumentWithTypeTag:
6980 handleArgumentWithTypeTagAttr(S, D, AL);
6981 break;
6982 case ParsedAttr::AT_TypeTagForDatatype:
6983 handleTypeTagForDatatypeAttr(S, D, AL);
6984 break;
6985 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:
6986 handleSimpleAttribute<AnyX86NoCallerSavedRegistersAttr>(S, D, AL);
6987 break;
6988 case ParsedAttr::AT_RenderScriptKernel:
6989 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, AL);
6990 break;
6991 // XRay attributes.
6992 case ParsedAttr::AT_XRayInstrument:
6993 handleSimpleAttribute<XRayInstrumentAttr>(S, D, AL);
6994 break;
6995 case ParsedAttr::AT_XRayLogArgs:
6996 handleXRayLogArgsAttr(S, D, AL);
6997 break;
6998
6999 // Move semantics attribute.
7000 case ParsedAttr::AT_Reinitializes:
7001 handleSimpleAttribute<ReinitializesAttr>(S, D, AL);
7002 break;
7003
7004 case ParsedAttr::AT_AlwaysDestroy:
7005 case ParsedAttr::AT_NoDestroy:
7006 handleDestroyAttr(S, D, AL);
7007 break;
7008
7009 case ParsedAttr::AT_Uninitialized:
7010 handleUninitializedAttr(S, D, AL);
7011 break;
7012
7013 case ParsedAttr::AT_ObjCExternallyRetained:
7014 handleObjCExternallyRetainedAttr(S, D, AL);
7015 break;
7016 }
7017 }
7018
7019 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
7020 /// attribute list to the specified decl, ignoring any type attributes.
ProcessDeclAttributeList(Scope * S,Decl * D,const ParsedAttributesView & AttrList,bool IncludeCXX11Attributes)7021 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
7022 const ParsedAttributesView &AttrList,
7023 bool IncludeCXX11Attributes) {
7024 if (AttrList.empty())
7025 return;
7026
7027 for (const ParsedAttr &AL : AttrList)
7028 ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
7029
7030 // FIXME: We should be able to handle these cases in TableGen.
7031 // GCC accepts
7032 // static int a9 __attribute__((weakref));
7033 // but that looks really pointless. We reject it.
7034 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
7035 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
7036 << cast<NamedDecl>(D);
7037 D->dropAttr<WeakRefAttr>();
7038 return;
7039 }
7040
7041 // FIXME: We should be able to handle this in TableGen as well. It would be
7042 // good to have a way to specify "these attributes must appear as a group",
7043 // for these. Additionally, it would be good to have a way to specify "these
7044 // attribute must never appear as a group" for attributes like cold and hot.
7045 if (!D->hasAttr<OpenCLKernelAttr>()) {
7046 // These attributes cannot be applied to a non-kernel function.
7047 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
7048 // FIXME: This emits a different error message than
7049 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
7050 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7051 D->setInvalidDecl();
7052 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
7053 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7054 D->setInvalidDecl();
7055 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
7056 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7057 D->setInvalidDecl();
7058 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
7059 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7060 D->setInvalidDecl();
7061 } else if (!D->hasAttr<CUDAGlobalAttr>()) {
7062 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7063 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7064 << A << ExpectedKernelFunction;
7065 D->setInvalidDecl();
7066 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
7067 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7068 << A << ExpectedKernelFunction;
7069 D->setInvalidDecl();
7070 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
7071 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7072 << A << ExpectedKernelFunction;
7073 D->setInvalidDecl();
7074 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
7075 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7076 << A << ExpectedKernelFunction;
7077 D->setInvalidDecl();
7078 }
7079 }
7080 }
7081
7082 // Do this check after processing D's attributes because the attribute
7083 // objc_method_family can change whether the given method is in the init
7084 // family, and it can be applied after objc_designated_initializer. This is a
7085 // bit of a hack, but we need it to be compatible with versions of clang that
7086 // processed the attribute list in the wrong order.
7087 if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
7088 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
7089 Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
7090 D->dropAttr<ObjCDesignatedInitializerAttr>();
7091 }
7092 }
7093
7094 // Helper for delayed processing TransparentUnion attribute.
ProcessDeclAttributeDelayed(Decl * D,const ParsedAttributesView & AttrList)7095 void Sema::ProcessDeclAttributeDelayed(Decl *D,
7096 const ParsedAttributesView &AttrList) {
7097 for (const ParsedAttr &AL : AttrList)
7098 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
7099 handleTransparentUnionAttr(*this, D, AL);
7100 break;
7101 }
7102 }
7103
7104 // Annotation attributes are the only attributes allowed after an access
7105 // specifier.
ProcessAccessDeclAttributeList(AccessSpecDecl * ASDecl,const ParsedAttributesView & AttrList)7106 bool Sema::ProcessAccessDeclAttributeList(
7107 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
7108 for (const ParsedAttr &AL : AttrList) {
7109 if (AL.getKind() == ParsedAttr::AT_Annotate) {
7110 ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
7111 } else {
7112 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
7113 return true;
7114 }
7115 }
7116 return false;
7117 }
7118
7119 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
7120 /// contains any decl attributes that we should warn about.
checkUnusedDeclAttributes(Sema & S,const ParsedAttributesView & A)7121 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
7122 for (const ParsedAttr &AL : A) {
7123 // Only warn if the attribute is an unignored, non-type attribute.
7124 if (AL.isUsedAsTypeAttr() || AL.isInvalid())
7125 continue;
7126 if (AL.getKind() == ParsedAttr::IgnoredAttribute)
7127 continue;
7128
7129 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
7130 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7131 << AL << AL.getRange();
7132 } else {
7133 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
7134 << AL.getRange();
7135 }
7136 }
7137 }
7138
7139 /// checkUnusedDeclAttributes - Given a declarator which is not being
7140 /// used to build a declaration, complain about any decl attributes
7141 /// which might be lying around on it.
checkUnusedDeclAttributes(Declarator & D)7142 void Sema::checkUnusedDeclAttributes(Declarator &D) {
7143 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
7144 ::checkUnusedDeclAttributes(*this, D.getAttributes());
7145 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
7146 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
7147 }
7148
7149 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
7150 /// \#pragma weak needs a non-definition decl and source may not have one.
DeclClonePragmaWeak(NamedDecl * ND,IdentifierInfo * II,SourceLocation Loc)7151 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7152 SourceLocation Loc) {
7153 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
7154 NamedDecl *NewD = nullptr;
7155 if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
7156 FunctionDecl *NewFD;
7157 // FIXME: Missing call to CheckFunctionDeclaration().
7158 // FIXME: Mangling?
7159 // FIXME: Is the qualifier info correct?
7160 // FIXME: Is the DeclContext correct?
7161 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
7162 Loc, Loc, DeclarationName(II),
7163 FD->getType(), FD->getTypeSourceInfo(),
7164 SC_None, false/*isInlineSpecified*/,
7165 FD->hasPrototype(),
7166 false/*isConstexprSpecified*/);
7167 NewD = NewFD;
7168
7169 if (FD->getQualifier())
7170 NewFD->setQualifierInfo(FD->getQualifierLoc());
7171
7172 // Fake up parameter variables; they are declared as if this were
7173 // a typedef.
7174 QualType FDTy = FD->getType();
7175 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
7176 SmallVector<ParmVarDecl*, 16> Params;
7177 for (const auto &AI : FT->param_types()) {
7178 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
7179 Param->setScopeInfo(0, Params.size());
7180 Params.push_back(Param);
7181 }
7182 NewFD->setParams(Params);
7183 }
7184 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
7185 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
7186 VD->getInnerLocStart(), VD->getLocation(), II,
7187 VD->getType(), VD->getTypeSourceInfo(),
7188 VD->getStorageClass());
7189 if (VD->getQualifier())
7190 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
7191 }
7192 return NewD;
7193 }
7194
7195 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
7196 /// applied to it, possibly with an alias.
DeclApplyPragmaWeak(Scope * S,NamedDecl * ND,WeakInfo & W)7197 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
7198 if (W.getUsed()) return; // only do this once
7199 W.setUsed(true);
7200 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
7201 IdentifierInfo *NDId = ND->getIdentifier();
7202 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
7203 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
7204 W.getLocation()));
7205 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
7206 WeakTopLevelDecl.push_back(NewD);
7207 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
7208 // to insert Decl at TU scope, sorry.
7209 DeclContext *SavedContext = CurContext;
7210 CurContext = Context.getTranslationUnitDecl();
7211 NewD->setDeclContext(CurContext);
7212 NewD->setLexicalDeclContext(CurContext);
7213 PushOnScopeChains(NewD, S);
7214 CurContext = SavedContext;
7215 } else { // just add weak to existing
7216 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
7217 }
7218 }
7219
ProcessPragmaWeak(Scope * S,Decl * D)7220 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
7221 // It's valid to "forward-declare" #pragma weak, in which case we
7222 // have to do this.
7223 LoadExternalWeakUndeclaredIdentifiers();
7224 if (!WeakUndeclaredIdentifiers.empty()) {
7225 NamedDecl *ND = nullptr;
7226 if (auto *VD = dyn_cast<VarDecl>(D))
7227 if (VD->isExternC())
7228 ND = VD;
7229 if (auto *FD = dyn_cast<FunctionDecl>(D))
7230 if (FD->isExternC())
7231 ND = FD;
7232 if (ND) {
7233 if (IdentifierInfo *Id = ND->getIdentifier()) {
7234 auto I = WeakUndeclaredIdentifiers.find(Id);
7235 if (I != WeakUndeclaredIdentifiers.end()) {
7236 WeakInfo W = I->second;
7237 DeclApplyPragmaWeak(S, ND, W);
7238 WeakUndeclaredIdentifiers[Id] = W;
7239 }
7240 }
7241 }
7242 }
7243 }
7244
7245 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
7246 /// it, apply them to D. This is a bit tricky because PD can have attributes
7247 /// specified in many different places, and we need to find and apply them all.
ProcessDeclAttributes(Scope * S,Decl * D,const Declarator & PD)7248 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
7249 // Apply decl attributes from the DeclSpec if present.
7250 if (!PD.getDeclSpec().getAttributes().empty())
7251 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
7252
7253 // Walk the declarator structure, applying decl attributes that were in a type
7254 // position to the decl itself. This handles cases like:
7255 // int *__attr__(x)** D;
7256 // when X is a decl attribute.
7257 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
7258 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
7259 /*IncludeCXX11Attributes=*/false);
7260
7261 // Finally, apply any attributes on the decl itself.
7262 ProcessDeclAttributeList(S, D, PD.getAttributes());
7263
7264 // Apply additional attributes specified by '#pragma clang attribute'.
7265 AddPragmaAttributes(S, D);
7266 }
7267
7268 /// Is the given declaration allowed to use a forbidden type?
7269 /// If so, it'll still be annotated with an attribute that makes it
7270 /// illegal to actually use.
isForbiddenTypeAllowed(Sema & S,Decl * D,const DelayedDiagnostic & diag,UnavailableAttr::ImplicitReason & reason)7271 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
7272 const DelayedDiagnostic &diag,
7273 UnavailableAttr::ImplicitReason &reason) {
7274 // Private ivars are always okay. Unfortunately, people don't
7275 // always properly make their ivars private, even in system headers.
7276 // Plus we need to make fields okay, too.
7277 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
7278 !isa<FunctionDecl>(D))
7279 return false;
7280
7281 // Silently accept unsupported uses of __weak in both user and system
7282 // declarations when it's been disabled, for ease of integration with
7283 // -fno-objc-arc files. We do have to take some care against attempts
7284 // to define such things; for now, we've only done that for ivars
7285 // and properties.
7286 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
7287 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
7288 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
7289 reason = UnavailableAttr::IR_ForbiddenWeak;
7290 return true;
7291 }
7292 }
7293
7294 // Allow all sorts of things in system headers.
7295 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
7296 // Currently, all the failures dealt with this way are due to ARC
7297 // restrictions.
7298 reason = UnavailableAttr::IR_ARCForbiddenType;
7299 return true;
7300 }
7301
7302 return false;
7303 }
7304
7305 /// Handle a delayed forbidden-type diagnostic.
handleDelayedForbiddenType(Sema & S,DelayedDiagnostic & DD,Decl * D)7306 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
7307 Decl *D) {
7308 auto Reason = UnavailableAttr::IR_None;
7309 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
7310 assert(Reason && "didn't set reason?");
7311 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
7312 return;
7313 }
7314 if (S.getLangOpts().ObjCAutoRefCount)
7315 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7316 // FIXME: we may want to suppress diagnostics for all
7317 // kind of forbidden type messages on unavailable functions.
7318 if (FD->hasAttr<UnavailableAttr>() &&
7319 DD.getForbiddenTypeDiagnostic() ==
7320 diag::err_arc_array_param_no_ownership) {
7321 DD.Triggered = true;
7322 return;
7323 }
7324 }
7325
7326 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
7327 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
7328 DD.Triggered = true;
7329 }
7330
getAttrForPlatform(ASTContext & Context,const Decl * D)7331 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
7332 const Decl *D) {
7333 // Check each AvailabilityAttr to find the one for this platform.
7334 for (const auto *A : D->attrs()) {
7335 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
7336 // FIXME: this is copied from CheckAvailability. We should try to
7337 // de-duplicate.
7338
7339 // Check if this is an App Extension "platform", and if so chop off
7340 // the suffix for matching with the actual platform.
7341 StringRef ActualPlatform = Avail->getPlatform()->getName();
7342 StringRef RealizedPlatform = ActualPlatform;
7343 if (Context.getLangOpts().AppExt) {
7344 size_t suffix = RealizedPlatform.rfind("_app_extension");
7345 if (suffix != StringRef::npos)
7346 RealizedPlatform = RealizedPlatform.slice(0, suffix);
7347 }
7348
7349 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
7350
7351 // Match the platform name.
7352 if (RealizedPlatform == TargetPlatform)
7353 return Avail;
7354 }
7355 }
7356 return nullptr;
7357 }
7358
7359 /// The diagnostic we should emit for \c D, and the declaration that
7360 /// originated it, or \c AR_Available.
7361 ///
7362 /// \param D The declaration to check.
7363 /// \param Message If non-null, this will be populated with the message from
7364 /// the availability attribute that is selected.
7365 /// \param ClassReceiver If we're checking the the method of a class message
7366 /// send, the class. Otherwise nullptr.
7367 static std::pair<AvailabilityResult, const NamedDecl *>
ShouldDiagnoseAvailabilityOfDecl(Sema & S,const NamedDecl * D,std::string * Message,ObjCInterfaceDecl * ClassReceiver)7368 ShouldDiagnoseAvailabilityOfDecl(Sema &S, const NamedDecl *D,
7369 std::string *Message,
7370 ObjCInterfaceDecl *ClassReceiver) {
7371 AvailabilityResult Result = D->getAvailability(Message);
7372
7373 // For typedefs, if the typedef declaration appears available look
7374 // to the underlying type to see if it is more restrictive.
7375 while (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
7376 if (Result == AR_Available) {
7377 if (const auto *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7378 D = TT->getDecl();
7379 Result = D->getAvailability(Message);
7380 continue;
7381 }
7382 }
7383 break;
7384 }
7385
7386 // Forward class declarations get their attributes from their definition.
7387 if (const auto *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
7388 if (IDecl->getDefinition()) {
7389 D = IDecl->getDefinition();
7390 Result = D->getAvailability(Message);
7391 }
7392 }
7393
7394 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
7395 if (Result == AR_Available) {
7396 const DeclContext *DC = ECD->getDeclContext();
7397 if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
7398 Result = TheEnumDecl->getAvailability(Message);
7399 D = TheEnumDecl;
7400 }
7401 }
7402
7403 // For +new, infer availability from -init.
7404 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7405 if (S.NSAPIObj && ClassReceiver) {
7406 ObjCMethodDecl *Init = ClassReceiver->lookupInstanceMethod(
7407 S.NSAPIObj->getInitSelector());
7408 if (Init && Result == AR_Available && MD->isClassMethod() &&
7409 MD->getSelector() == S.NSAPIObj->getNewSelector() &&
7410 MD->definedInNSObject(S.getASTContext())) {
7411 Result = Init->getAvailability(Message);
7412 D = Init;
7413 }
7414 }
7415 }
7416
7417 return {Result, D};
7418 }
7419
7420
7421 /// whether we should emit a diagnostic for \c K and \c DeclVersion in
7422 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
7423 /// in a deprecated context, but not the other way around.
7424 static bool
ShouldDiagnoseAvailabilityInContext(Sema & S,AvailabilityResult K,VersionTuple DeclVersion,Decl * Ctx,const NamedDecl * OffendingDecl)7425 ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
7426 VersionTuple DeclVersion, Decl *Ctx,
7427 const NamedDecl *OffendingDecl) {
7428 assert(K != AR_Available && "Expected an unavailable declaration here!");
7429
7430 // Checks if we should emit the availability diagnostic in the context of C.
7431 auto CheckContext = [&](const Decl *C) {
7432 if (K == AR_NotYetIntroduced) {
7433 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
7434 if (AA->getIntroduced() >= DeclVersion)
7435 return true;
7436 } else if (K == AR_Deprecated) {
7437 if (C->isDeprecated())
7438 return true;
7439 } else if (K == AR_Unavailable) {
7440 // It is perfectly fine to refer to an 'unavailable' Objective-C method
7441 // when it is referenced from within the @implementation itself. In this
7442 // context, we interpret unavailable as a form of access control.
7443 if (const auto *MD = dyn_cast<ObjCMethodDecl>(OffendingDecl)) {
7444 if (const auto *Impl = dyn_cast<ObjCImplDecl>(C)) {
7445 if (MD->getClassInterface() == Impl->getClassInterface())
7446 return true;
7447 }
7448 }
7449 }
7450
7451 if (C->isUnavailable())
7452 return true;
7453 return false;
7454 };
7455
7456 do {
7457 if (CheckContext(Ctx))
7458 return false;
7459
7460 // An implementation implicitly has the availability of the interface.
7461 // Unless it is "+load" method.
7462 if (const auto *MethodD = dyn_cast<ObjCMethodDecl>(Ctx))
7463 if (MethodD->isClassMethod() &&
7464 MethodD->getSelector().getAsString() == "load")
7465 return true;
7466
7467 if (const auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
7468 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7469 if (CheckContext(Interface))
7470 return false;
7471 }
7472 // A category implicitly has the availability of the interface.
7473 else if (const auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
7474 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7475 if (CheckContext(Interface))
7476 return false;
7477 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
7478
7479 return true;
7480 }
7481
7482 static bool
shouldDiagnoseAvailabilityByDefault(const ASTContext & Context,const VersionTuple & DeploymentVersion,const VersionTuple & DeclVersion)7483 shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
7484 const VersionTuple &DeploymentVersion,
7485 const VersionTuple &DeclVersion) {
7486 const auto &Triple = Context.getTargetInfo().getTriple();
7487 VersionTuple ForceAvailabilityFromVersion;
7488 switch (Triple.getOS()) {
7489 case llvm::Triple::IOS:
7490 case llvm::Triple::TvOS:
7491 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
7492 break;
7493 case llvm::Triple::WatchOS:
7494 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
7495 break;
7496 case llvm::Triple::Darwin:
7497 case llvm::Triple::MacOSX:
7498 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
7499 break;
7500 default:
7501 // New targets should always warn about availability.
7502 return Triple.getVendor() == llvm::Triple::Apple;
7503 }
7504 return DeploymentVersion >= ForceAvailabilityFromVersion ||
7505 DeclVersion >= ForceAvailabilityFromVersion;
7506 }
7507
findEnclosingDeclToAnnotate(Decl * OrigCtx)7508 static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
7509 for (Decl *Ctx = OrigCtx; Ctx;
7510 Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
7511 if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
7512 return cast<NamedDecl>(Ctx);
7513 if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
7514 if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
7515 return Imp->getClassInterface();
7516 return CD;
7517 }
7518 }
7519
7520 return dyn_cast<NamedDecl>(OrigCtx);
7521 }
7522
7523 namespace {
7524
7525 struct AttributeInsertion {
7526 StringRef Prefix;
7527 SourceLocation Loc;
7528 StringRef Suffix;
7529
createInsertionAfter__anonc9af26d70811::AttributeInsertion7530 static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
7531 return {" ", D->getEndLoc(), ""};
7532 }
createInsertionAfter__anonc9af26d70811::AttributeInsertion7533 static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
7534 return {" ", Loc, ""};
7535 }
createInsertionBefore__anonc9af26d70811::AttributeInsertion7536 static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
7537 return {"", D->getBeginLoc(), "\n"};
7538 }
7539 };
7540
7541 } // end anonymous namespace
7542
7543 /// Tries to parse a string as ObjC method name.
7544 ///
7545 /// \param Name The string to parse. Expected to originate from availability
7546 /// attribute argument.
7547 /// \param SlotNames The vector that will be populated with slot names. In case
7548 /// of unsuccessful parsing can contain invalid data.
7549 /// \returns A number of method parameters if parsing was successful, None
7550 /// otherwise.
7551 static Optional<unsigned>
tryParseObjCMethodName(StringRef Name,SmallVectorImpl<StringRef> & SlotNames,const LangOptions & LangOpts)7552 tryParseObjCMethodName(StringRef Name, SmallVectorImpl<StringRef> &SlotNames,
7553 const LangOptions &LangOpts) {
7554 // Accept replacements starting with - or + as valid ObjC method names.
7555 if (!Name.empty() && (Name.front() == '-' || Name.front() == '+'))
7556 Name = Name.drop_front(1);
7557 if (Name.empty())
7558 return None;
7559 Name.split(SlotNames, ':');
7560 unsigned NumParams;
7561 if (Name.back() == ':') {
7562 // Remove an empty string at the end that doesn't represent any slot.
7563 SlotNames.pop_back();
7564 NumParams = SlotNames.size();
7565 } else {
7566 if (SlotNames.size() != 1)
7567 // Not a valid method name, just a colon-separated string.
7568 return None;
7569 NumParams = 0;
7570 }
7571 // Verify all slot names are valid.
7572 bool AllowDollar = LangOpts.DollarIdents;
7573 for (StringRef S : SlotNames) {
7574 if (S.empty())
7575 continue;
7576 if (!isValidIdentifier(S, AllowDollar))
7577 return None;
7578 }
7579 return NumParams;
7580 }
7581
7582 /// Returns a source location in which it's appropriate to insert a new
7583 /// attribute for the given declaration \D.
7584 static Optional<AttributeInsertion>
createAttributeInsertion(const NamedDecl * D,const SourceManager & SM,const LangOptions & LangOpts)7585 createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
7586 const LangOptions &LangOpts) {
7587 if (isa<ObjCPropertyDecl>(D))
7588 return AttributeInsertion::createInsertionAfter(D);
7589 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7590 if (MD->hasBody())
7591 return None;
7592 return AttributeInsertion::createInsertionAfter(D);
7593 }
7594 if (const auto *TD = dyn_cast<TagDecl>(D)) {
7595 SourceLocation Loc =
7596 Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
7597 if (Loc.isInvalid())
7598 return None;
7599 // Insert after the 'struct'/whatever keyword.
7600 return AttributeInsertion::createInsertionAfter(Loc);
7601 }
7602 return AttributeInsertion::createInsertionBefore(D);
7603 }
7604
7605 /// Actually emit an availability diagnostic for a reference to an unavailable
7606 /// decl.
7607 ///
7608 /// \param Ctx The context that the reference occurred in
7609 /// \param ReferringDecl The exact declaration that was referenced.
7610 /// \param OffendingDecl A related decl to \c ReferringDecl that has an
7611 /// availability attribute corresponding to \c K attached to it. Note that this
7612 /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
7613 /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
7614 /// and OffendingDecl is the EnumDecl.
DoEmitAvailabilityWarning(Sema & S,AvailabilityResult K,Decl * Ctx,const NamedDecl * ReferringDecl,const NamedDecl * OffendingDecl,StringRef Message,ArrayRef<SourceLocation> Locs,const ObjCInterfaceDecl * UnknownObjCClass,const ObjCPropertyDecl * ObjCProperty,bool ObjCPropertyAccess)7615 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
7616 Decl *Ctx, const NamedDecl *ReferringDecl,
7617 const NamedDecl *OffendingDecl,
7618 StringRef Message,
7619 ArrayRef<SourceLocation> Locs,
7620 const ObjCInterfaceDecl *UnknownObjCClass,
7621 const ObjCPropertyDecl *ObjCProperty,
7622 bool ObjCPropertyAccess) {
7623 // Diagnostics for deprecated or unavailable.
7624 unsigned diag, diag_message, diag_fwdclass_message;
7625 unsigned diag_available_here = diag::note_availability_specified_here;
7626 SourceLocation NoteLocation = OffendingDecl->getLocation();
7627
7628 // Matches 'diag::note_property_attribute' options.
7629 unsigned property_note_select;
7630
7631 // Matches diag::note_availability_specified_here.
7632 unsigned available_here_select_kind;
7633
7634 VersionTuple DeclVersion;
7635 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
7636 DeclVersion = AA->getIntroduced();
7637
7638 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx,
7639 OffendingDecl))
7640 return;
7641
7642 SourceLocation Loc = Locs.front();
7643
7644 // The declaration can have multiple availability attributes, we are looking
7645 // at one of them.
7646 const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
7647 if (A && A->isInherited()) {
7648 for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
7649 Redecl = Redecl->getPreviousDecl()) {
7650 const AvailabilityAttr *AForRedecl =
7651 getAttrForPlatform(S.Context, Redecl);
7652 if (AForRedecl && !AForRedecl->isInherited()) {
7653 // If D is a declaration with inherited attributes, the note should
7654 // point to the declaration with actual attributes.
7655 NoteLocation = Redecl->getLocation();
7656 break;
7657 }
7658 }
7659 }
7660
7661 switch (K) {
7662 case AR_NotYetIntroduced: {
7663 // We would like to emit the diagnostic even if -Wunguarded-availability is
7664 // not specified for deployment targets >= to iOS 11 or equivalent or
7665 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7666 // later.
7667 const AvailabilityAttr *AA =
7668 getAttrForPlatform(S.getASTContext(), OffendingDecl);
7669 VersionTuple Introduced = AA->getIntroduced();
7670
7671 bool UseNewWarning = shouldDiagnoseAvailabilityByDefault(
7672 S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
7673 Introduced);
7674 unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new
7675 : diag::warn_unguarded_availability;
7676
7677 std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
7678 S.getASTContext().getTargetInfo().getPlatformName());
7679
7680 S.Diag(Loc, Warning) << OffendingDecl << PlatformName
7681 << Introduced.getAsString();
7682
7683 S.Diag(OffendingDecl->getLocation(),
7684 diag::note_partial_availability_specified_here)
7685 << OffendingDecl << PlatformName << Introduced.getAsString()
7686 << S.Context.getTargetInfo().getPlatformMinVersion().getAsString();
7687
7688 if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
7689 if (const auto *TD = dyn_cast<TagDecl>(Enclosing))
7690 if (TD->getDeclName().isEmpty()) {
7691 S.Diag(TD->getLocation(),
7692 diag::note_decl_unguarded_availability_silence)
7693 << /*Anonymous*/ 1 << TD->getKindName();
7694 return;
7695 }
7696 auto FixitNoteDiag =
7697 S.Diag(Enclosing->getLocation(),
7698 diag::note_decl_unguarded_availability_silence)
7699 << /*Named*/ 0 << Enclosing;
7700 // Don't offer a fixit for declarations with availability attributes.
7701 if (Enclosing->hasAttr<AvailabilityAttr>())
7702 return;
7703 if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
7704 return;
7705 Optional<AttributeInsertion> Insertion = createAttributeInsertion(
7706 Enclosing, S.getSourceManager(), S.getLangOpts());
7707 if (!Insertion)
7708 return;
7709 std::string PlatformName =
7710 AvailabilityAttr::getPlatformNameSourceSpelling(
7711 S.getASTContext().getTargetInfo().getPlatformName())
7712 .lower();
7713 std::string Introduced =
7714 OffendingDecl->getVersionIntroduced().getAsString();
7715 FixitNoteDiag << FixItHint::CreateInsertion(
7716 Insertion->Loc,
7717 (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
7718 "(" + Introduced + "))" + Insertion->Suffix)
7719 .str());
7720 }
7721 return;
7722 }
7723 case AR_Deprecated:
7724 diag = !ObjCPropertyAccess ? diag::warn_deprecated
7725 : diag::warn_property_method_deprecated;
7726 diag_message = diag::warn_deprecated_message;
7727 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
7728 property_note_select = /* deprecated */ 0;
7729 available_here_select_kind = /* deprecated */ 2;
7730 if (const auto *AL = OffendingDecl->getAttr<DeprecatedAttr>())
7731 NoteLocation = AL->getLocation();
7732 break;
7733
7734 case AR_Unavailable:
7735 diag = !ObjCPropertyAccess ? diag::err_unavailable
7736 : diag::err_property_method_unavailable;
7737 diag_message = diag::err_unavailable_message;
7738 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
7739 property_note_select = /* unavailable */ 1;
7740 available_here_select_kind = /* unavailable */ 0;
7741
7742 if (auto AL = OffendingDecl->getAttr<UnavailableAttr>()) {
7743 if (AL->isImplicit() && AL->getImplicitReason()) {
7744 // Most of these failures are due to extra restrictions in ARC;
7745 // reflect that in the primary diagnostic when applicable.
7746 auto flagARCError = [&] {
7747 if (S.getLangOpts().ObjCAutoRefCount &&
7748 S.getSourceManager().isInSystemHeader(
7749 OffendingDecl->getLocation()))
7750 diag = diag::err_unavailable_in_arc;
7751 };
7752
7753 switch (AL->getImplicitReason()) {
7754 case UnavailableAttr::IR_None: break;
7755
7756 case UnavailableAttr::IR_ARCForbiddenType:
7757 flagARCError();
7758 diag_available_here = diag::note_arc_forbidden_type;
7759 break;
7760
7761 case UnavailableAttr::IR_ForbiddenWeak:
7762 if (S.getLangOpts().ObjCWeakRuntime)
7763 diag_available_here = diag::note_arc_weak_disabled;
7764 else
7765 diag_available_here = diag::note_arc_weak_no_runtime;
7766 break;
7767
7768 case UnavailableAttr::IR_ARCForbiddenConversion:
7769 flagARCError();
7770 diag_available_here = diag::note_performs_forbidden_arc_conversion;
7771 break;
7772
7773 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
7774 flagARCError();
7775 diag_available_here = diag::note_arc_init_returns_unrelated;
7776 break;
7777
7778 case UnavailableAttr::IR_ARCFieldWithOwnership:
7779 flagARCError();
7780 diag_available_here = diag::note_arc_field_with_ownership;
7781 break;
7782 }
7783 }
7784 }
7785 break;
7786
7787 case AR_Available:
7788 llvm_unreachable("Warning for availability of available declaration?");
7789 }
7790
7791 SmallVector<FixItHint, 12> FixIts;
7792 if (K == AR_Deprecated) {
7793 StringRef Replacement;
7794 if (auto AL = OffendingDecl->getAttr<DeprecatedAttr>())
7795 Replacement = AL->getReplacement();
7796 if (auto AL = getAttrForPlatform(S.Context, OffendingDecl))
7797 Replacement = AL->getReplacement();
7798
7799 CharSourceRange UseRange;
7800 if (!Replacement.empty())
7801 UseRange =
7802 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
7803 if (UseRange.isValid()) {
7804 if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(ReferringDecl)) {
7805 Selector Sel = MethodDecl->getSelector();
7806 SmallVector<StringRef, 12> SelectorSlotNames;
7807 Optional<unsigned> NumParams = tryParseObjCMethodName(
7808 Replacement, SelectorSlotNames, S.getLangOpts());
7809 if (NumParams && NumParams.getValue() == Sel.getNumArgs()) {
7810 assert(SelectorSlotNames.size() == Locs.size());
7811 for (unsigned I = 0; I < Locs.size(); ++I) {
7812 if (!Sel.getNameForSlot(I).empty()) {
7813 CharSourceRange NameRange = CharSourceRange::getCharRange(
7814 Locs[I], S.getLocForEndOfToken(Locs[I]));
7815 FixIts.push_back(FixItHint::CreateReplacement(
7816 NameRange, SelectorSlotNames[I]));
7817 } else
7818 FixIts.push_back(
7819 FixItHint::CreateInsertion(Locs[I], SelectorSlotNames[I]));
7820 }
7821 } else
7822 FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
7823 } else
7824 FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
7825 }
7826 }
7827
7828 if (!Message.empty()) {
7829 S.Diag(Loc, diag_message) << ReferringDecl << Message << FixIts;
7830 if (ObjCProperty)
7831 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7832 << ObjCProperty->getDeclName() << property_note_select;
7833 } else if (!UnknownObjCClass) {
7834 S.Diag(Loc, diag) << ReferringDecl << FixIts;
7835 if (ObjCProperty)
7836 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7837 << ObjCProperty->getDeclName() << property_note_select;
7838 } else {
7839 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << FixIts;
7840 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7841 }
7842
7843 S.Diag(NoteLocation, diag_available_here)
7844 << OffendingDecl << available_here_select_kind;
7845 }
7846
handleDelayedAvailabilityCheck(Sema & S,DelayedDiagnostic & DD,Decl * Ctx)7847 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7848 Decl *Ctx) {
7849 assert(DD.Kind == DelayedDiagnostic::Availability &&
7850 "Expected an availability diagnostic here");
7851
7852 DD.Triggered = true;
7853 DoEmitAvailabilityWarning(
7854 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
7855 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(),
7856 DD.getAvailabilitySelectorLocs(), DD.getUnknownObjCClass(),
7857 DD.getObjCProperty(), false);
7858 }
7859
PopParsingDeclaration(ParsingDeclState state,Decl * decl)7860 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7861 assert(DelayedDiagnostics.getCurrentPool());
7862 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7863 DelayedDiagnostics.popWithoutEmitting(state);
7864
7865 // When delaying diagnostics to run in the context of a parsed
7866 // declaration, we only want to actually emit anything if parsing
7867 // succeeds.
7868 if (!decl) return;
7869
7870 // We emit all the active diagnostics in this pool or any of its
7871 // parents. In general, we'll get one pool for the decl spec
7872 // and a child pool for each declarator; in a decl group like:
7873 // deprecated_typedef foo, *bar, baz();
7874 // only the declarator pops will be passed decls. This is correct;
7875 // we really do need to consider delayed diagnostics from the decl spec
7876 // for each of the different declarations.
7877 const DelayedDiagnosticPool *pool = &poppedPool;
7878 do {
7879 bool AnyAccessFailures = false;
7880 for (DelayedDiagnosticPool::pool_iterator
7881 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7882 // This const_cast is a bit lame. Really, Triggered should be mutable.
7883 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7884 if (diag.Triggered)
7885 continue;
7886
7887 switch (diag.Kind) {
7888 case DelayedDiagnostic::Availability:
7889 // Don't bother giving deprecation/unavailable diagnostics if
7890 // the decl is invalid.
7891 if (!decl->isInvalidDecl())
7892 handleDelayedAvailabilityCheck(*this, diag, decl);
7893 break;
7894
7895 case DelayedDiagnostic::Access:
7896 // Only produce one access control diagnostic for a structured binding
7897 // declaration: we don't need to tell the user that all the fields are
7898 // inaccessible one at a time.
7899 if (AnyAccessFailures && isa<DecompositionDecl>(decl))
7900 continue;
7901 HandleDelayedAccessCheck(diag, decl);
7902 if (diag.Triggered)
7903 AnyAccessFailures = true;
7904 break;
7905
7906 case DelayedDiagnostic::ForbiddenType:
7907 handleDelayedForbiddenType(*this, diag, decl);
7908 break;
7909 }
7910 }
7911 } while ((pool = pool->getParent()));
7912 }
7913
7914 /// Given a set of delayed diagnostics, re-emit them as if they had
7915 /// been delayed in the current context instead of in the given pool.
7916 /// Essentially, this just moves them to the current pool.
redelayDiagnostics(DelayedDiagnosticPool & pool)7917 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7918 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7919 assert(curPool && "re-emitting in undelayed context not supported");
7920 curPool->steal(pool);
7921 }
7922
EmitAvailabilityWarning(Sema & S,AvailabilityResult AR,const NamedDecl * ReferringDecl,const NamedDecl * OffendingDecl,StringRef Message,ArrayRef<SourceLocation> Locs,const ObjCInterfaceDecl * UnknownObjCClass,const ObjCPropertyDecl * ObjCProperty,bool ObjCPropertyAccess)7923 static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
7924 const NamedDecl *ReferringDecl,
7925 const NamedDecl *OffendingDecl,
7926 StringRef Message,
7927 ArrayRef<SourceLocation> Locs,
7928 const ObjCInterfaceDecl *UnknownObjCClass,
7929 const ObjCPropertyDecl *ObjCProperty,
7930 bool ObjCPropertyAccess) {
7931 // Delay if we're currently parsing a declaration.
7932 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7933 S.DelayedDiagnostics.add(
7934 DelayedDiagnostic::makeAvailability(
7935 AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass,
7936 ObjCProperty, Message, ObjCPropertyAccess));
7937 return;
7938 }
7939
7940 Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
7941 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
7942 Message, Locs, UnknownObjCClass, ObjCProperty,
7943 ObjCPropertyAccess);
7944 }
7945
7946 namespace {
7947
7948 /// Returns true if the given statement can be a body-like child of \p Parent.
isBodyLikeChildStmt(const Stmt * S,const Stmt * Parent)7949 bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
7950 switch (Parent->getStmtClass()) {
7951 case Stmt::IfStmtClass:
7952 return cast<IfStmt>(Parent)->getThen() == S ||
7953 cast<IfStmt>(Parent)->getElse() == S;
7954 case Stmt::WhileStmtClass:
7955 return cast<WhileStmt>(Parent)->getBody() == S;
7956 case Stmt::DoStmtClass:
7957 return cast<DoStmt>(Parent)->getBody() == S;
7958 case Stmt::ForStmtClass:
7959 return cast<ForStmt>(Parent)->getBody() == S;
7960 case Stmt::CXXForRangeStmtClass:
7961 return cast<CXXForRangeStmt>(Parent)->getBody() == S;
7962 case Stmt::ObjCForCollectionStmtClass:
7963 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
7964 case Stmt::CaseStmtClass:
7965 case Stmt::DefaultStmtClass:
7966 return cast<SwitchCase>(Parent)->getSubStmt() == S;
7967 default:
7968 return false;
7969 }
7970 }
7971
7972 class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
7973 const Stmt *Target;
7974
7975 public:
VisitStmt(Stmt * S)7976 bool VisitStmt(Stmt *S) { return S != Target; }
7977
7978 /// Returns true if the given statement is present in the given declaration.
isContained(const Stmt * Target,const Decl * D)7979 static bool isContained(const Stmt *Target, const Decl *D) {
7980 StmtUSEFinder Visitor;
7981 Visitor.Target = Target;
7982 return !Visitor.TraverseDecl(const_cast<Decl *>(D));
7983 }
7984 };
7985
7986 /// Traverses the AST and finds the last statement that used a given
7987 /// declaration.
7988 class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
7989 const Decl *D;
7990
7991 public:
VisitDeclRefExpr(DeclRefExpr * DRE)7992 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7993 if (DRE->getDecl() == D)
7994 return false;
7995 return true;
7996 }
7997
findLastStmtThatUsesDecl(const Decl * D,const CompoundStmt * Scope)7998 static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
7999 const CompoundStmt *Scope) {
8000 LastDeclUSEFinder Visitor;
8001 Visitor.D = D;
8002 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
8003 const Stmt *S = *I;
8004 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
8005 return S;
8006 }
8007 return nullptr;
8008 }
8009 };
8010
8011 /// This class implements -Wunguarded-availability.
8012 ///
8013 /// This is done with a traversal of the AST of a function that makes reference
8014 /// to a partially available declaration. Whenever we encounter an \c if of the
8015 /// form: \c if(@available(...)), we use the version from the condition to visit
8016 /// the then statement.
8017 class DiagnoseUnguardedAvailability
8018 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
8019 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
8020
8021 Sema &SemaRef;
8022 Decl *Ctx;
8023
8024 /// Stack of potentially nested 'if (@available(...))'s.
8025 SmallVector<VersionTuple, 8> AvailabilityStack;
8026 SmallVector<const Stmt *, 16> StmtStack;
8027
8028 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range,
8029 ObjCInterfaceDecl *ClassReceiver = nullptr);
8030
8031 public:
DiagnoseUnguardedAvailability(Sema & SemaRef,Decl * Ctx)8032 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
8033 : SemaRef(SemaRef), Ctx(Ctx) {
8034 AvailabilityStack.push_back(
8035 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
8036 }
8037
TraverseDecl(Decl * D)8038 bool TraverseDecl(Decl *D) {
8039 // Avoid visiting nested functions to prevent duplicate warnings.
8040 if (!D || isa<FunctionDecl>(D))
8041 return true;
8042 return Base::TraverseDecl(D);
8043 }
8044
TraverseStmt(Stmt * S)8045 bool TraverseStmt(Stmt *S) {
8046 if (!S)
8047 return true;
8048 StmtStack.push_back(S);
8049 bool Result = Base::TraverseStmt(S);
8050 StmtStack.pop_back();
8051 return Result;
8052 }
8053
IssueDiagnostics(Stmt * S)8054 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
8055
8056 bool TraverseIfStmt(IfStmt *If);
8057
TraverseLambdaExpr(LambdaExpr * E)8058 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
8059
8060 // for 'case X:' statements, don't bother looking at the 'X'; it can't lead
8061 // to any useful diagnostics.
TraverseCaseStmt(CaseStmt * CS)8062 bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); }
8063
VisitObjCPropertyRefExpr(ObjCPropertyRefExpr * PRE)8064 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
8065 if (PRE->isClassReceiver())
8066 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
8067 return true;
8068 }
8069
VisitObjCMessageExpr(ObjCMessageExpr * Msg)8070 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
8071 if (ObjCMethodDecl *D = Msg->getMethodDecl()) {
8072 ObjCInterfaceDecl *ID = nullptr;
8073 QualType ReceiverTy = Msg->getClassReceiver();
8074 if (!ReceiverTy.isNull() && ReceiverTy->getAsObjCInterfaceType())
8075 ID = ReceiverTy->getAsObjCInterfaceType()->getInterface();
8076
8077 DiagnoseDeclAvailability(
8078 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getEndLoc()), ID);
8079 }
8080 return true;
8081 }
8082
VisitDeclRefExpr(DeclRefExpr * DRE)8083 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
8084 DiagnoseDeclAvailability(DRE->getDecl(),
8085 SourceRange(DRE->getBeginLoc(), DRE->getEndLoc()));
8086 return true;
8087 }
8088
VisitMemberExpr(MemberExpr * ME)8089 bool VisitMemberExpr(MemberExpr *ME) {
8090 DiagnoseDeclAvailability(ME->getMemberDecl(),
8091 SourceRange(ME->getBeginLoc(), ME->getEndLoc()));
8092 return true;
8093 }
8094
VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr * E)8095 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
8096 SemaRef.Diag(E->getBeginLoc(), diag::warn_at_available_unchecked_use)
8097 << (!SemaRef.getLangOpts().ObjC);
8098 return true;
8099 }
8100
8101 bool VisitTypeLoc(TypeLoc Ty);
8102 };
8103
DiagnoseDeclAvailability(NamedDecl * D,SourceRange Range,ObjCInterfaceDecl * ReceiverClass)8104 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
8105 NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ReceiverClass) {
8106 AvailabilityResult Result;
8107 const NamedDecl *OffendingDecl;
8108 std::tie(Result, OffendingDecl) =
8109 ShouldDiagnoseAvailabilityOfDecl(SemaRef, D, nullptr, ReceiverClass);
8110 if (Result != AR_Available) {
8111 // All other diagnostic kinds have already been handled in
8112 // DiagnoseAvailabilityOfDecl.
8113 if (Result != AR_NotYetIntroduced)
8114 return;
8115
8116 const AvailabilityAttr *AA =
8117 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
8118 VersionTuple Introduced = AA->getIntroduced();
8119
8120 if (AvailabilityStack.back() >= Introduced)
8121 return;
8122
8123 // If the context of this function is less available than D, we should not
8124 // emit a diagnostic.
8125 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx,
8126 OffendingDecl))
8127 return;
8128
8129 // We would like to emit the diagnostic even if -Wunguarded-availability is
8130 // not specified for deployment targets >= to iOS 11 or equivalent or
8131 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
8132 // later.
8133 unsigned DiagKind =
8134 shouldDiagnoseAvailabilityByDefault(
8135 SemaRef.Context,
8136 SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
8137 ? diag::warn_unguarded_availability_new
8138 : diag::warn_unguarded_availability;
8139
8140 std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
8141 SemaRef.getASTContext().getTargetInfo().getPlatformName());
8142
8143 SemaRef.Diag(Range.getBegin(), DiagKind)
8144 << Range << D << PlatformName << Introduced.getAsString();
8145
8146 SemaRef.Diag(OffendingDecl->getLocation(),
8147 diag::note_partial_availability_specified_here)
8148 << OffendingDecl << PlatformName << Introduced.getAsString()
8149 << SemaRef.Context.getTargetInfo()
8150 .getPlatformMinVersion()
8151 .getAsString();
8152
8153 auto FixitDiag =
8154 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
8155 << Range << D
8156 << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0
8157 : /*__builtin_available*/ 1);
8158
8159 // Find the statement which should be enclosed in the if @available check.
8160 if (StmtStack.empty())
8161 return;
8162 const Stmt *StmtOfUse = StmtStack.back();
8163 const CompoundStmt *Scope = nullptr;
8164 for (const Stmt *S : llvm::reverse(StmtStack)) {
8165 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
8166 Scope = CS;
8167 break;
8168 }
8169 if (isBodyLikeChildStmt(StmtOfUse, S)) {
8170 // The declaration won't be seen outside of the statement, so we don't
8171 // have to wrap the uses of any declared variables in if (@available).
8172 // Therefore we can avoid setting Scope here.
8173 break;
8174 }
8175 StmtOfUse = S;
8176 }
8177 const Stmt *LastStmtOfUse = nullptr;
8178 if (isa<DeclStmt>(StmtOfUse) && Scope) {
8179 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
8180 if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
8181 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
8182 break;
8183 }
8184 }
8185 }
8186
8187 const SourceManager &SM = SemaRef.getSourceManager();
8188 SourceLocation IfInsertionLoc =
8189 SM.getExpansionLoc(StmtOfUse->getBeginLoc());
8190 SourceLocation StmtEndLoc =
8191 SM.getExpansionRange(
8192 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc())
8193 .getEnd();
8194 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
8195 return;
8196
8197 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
8198 const char *ExtraIndentation = " ";
8199 std::string FixItString;
8200 llvm::raw_string_ostream FixItOS(FixItString);
8201 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC ? "@available"
8202 : "__builtin_available")
8203 << "("
8204 << AvailabilityAttr::getPlatformNameSourceSpelling(
8205 SemaRef.getASTContext().getTargetInfo().getPlatformName())
8206 << " " << Introduced.getAsString() << ", *)) {\n"
8207 << Indentation << ExtraIndentation;
8208 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
8209 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
8210 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
8211 /*SkipTrailingWhitespaceAndNewLine=*/false);
8212 if (ElseInsertionLoc.isInvalid())
8213 ElseInsertionLoc =
8214 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
8215 FixItOS.str().clear();
8216 FixItOS << "\n"
8217 << Indentation << "} else {\n"
8218 << Indentation << ExtraIndentation
8219 << "// Fallback on earlier versions\n"
8220 << Indentation << "}";
8221 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
8222 }
8223 }
8224
VisitTypeLoc(TypeLoc Ty)8225 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
8226 const Type *TyPtr = Ty.getTypePtr();
8227 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
8228
8229 if (Range.isInvalid())
8230 return true;
8231
8232 if (const auto *TT = dyn_cast<TagType>(TyPtr)) {
8233 TagDecl *TD = TT->getDecl();
8234 DiagnoseDeclAvailability(TD, Range);
8235
8236 } else if (const auto *TD = dyn_cast<TypedefType>(TyPtr)) {
8237 TypedefNameDecl *D = TD->getDecl();
8238 DiagnoseDeclAvailability(D, Range);
8239
8240 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
8241 if (NamedDecl *D = ObjCO->getInterface())
8242 DiagnoseDeclAvailability(D, Range);
8243 }
8244
8245 return true;
8246 }
8247
TraverseIfStmt(IfStmt * If)8248 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
8249 VersionTuple CondVersion;
8250 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
8251 CondVersion = E->getVersion();
8252
8253 // If we're using the '*' case here or if this check is redundant, then we
8254 // use the enclosing version to check both branches.
8255 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
8256 return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
8257 } else {
8258 // This isn't an availability checking 'if', we can just continue.
8259 return Base::TraverseIfStmt(If);
8260 }
8261
8262 AvailabilityStack.push_back(CondVersion);
8263 bool ShouldContinue = TraverseStmt(If->getThen());
8264 AvailabilityStack.pop_back();
8265
8266 return ShouldContinue && TraverseStmt(If->getElse());
8267 }
8268
8269 } // end anonymous namespace
8270
DiagnoseUnguardedAvailabilityViolations(Decl * D)8271 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
8272 Stmt *Body = nullptr;
8273
8274 if (auto *FD = D->getAsFunction()) {
8275 // FIXME: We only examine the pattern decl for availability violations now,
8276 // but we should also examine instantiated templates.
8277 if (FD->isTemplateInstantiation())
8278 return;
8279
8280 Body = FD->getBody();
8281 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
8282 Body = MD->getBody();
8283 else if (auto *BD = dyn_cast<BlockDecl>(D))
8284 Body = BD->getBody();
8285
8286 assert(Body && "Need a body here!");
8287
8288 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
8289 }
8290
DiagnoseAvailabilityOfDecl(NamedDecl * D,ArrayRef<SourceLocation> Locs,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess,bool AvoidPartialAvailabilityChecks,ObjCInterfaceDecl * ClassReceiver)8291 void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D,
8292 ArrayRef<SourceLocation> Locs,
8293 const ObjCInterfaceDecl *UnknownObjCClass,
8294 bool ObjCPropertyAccess,
8295 bool AvoidPartialAvailabilityChecks,
8296 ObjCInterfaceDecl *ClassReceiver) {
8297 std::string Message;
8298 AvailabilityResult Result;
8299 const NamedDecl* OffendingDecl;
8300 // See if this declaration is unavailable, deprecated, or partial.
8301 std::tie(Result, OffendingDecl) =
8302 ShouldDiagnoseAvailabilityOfDecl(*this, D, &Message, ClassReceiver);
8303 if (Result == AR_Available)
8304 return;
8305
8306 if (Result == AR_NotYetIntroduced) {
8307 if (AvoidPartialAvailabilityChecks)
8308 return;
8309
8310 // We need to know the @available context in the current function to
8311 // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
8312 // when we're done parsing the current function.
8313 if (getCurFunctionOrMethodDecl()) {
8314 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
8315 return;
8316 } else if (getCurBlock() || getCurLambda()) {
8317 getCurFunction()->HasPotentialAvailabilityViolations = true;
8318 return;
8319 }
8320 }
8321
8322 const ObjCPropertyDecl *ObjCPDecl = nullptr;
8323 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
8324 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
8325 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
8326 if (PDeclResult == Result)
8327 ObjCPDecl = PD;
8328 }
8329 }
8330
8331 EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Locs,
8332 UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
8333 }
8334