Debian Codegraph @

clang/lib/Sema/SemaDeclAttr.cpp

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