clang 19.0.0git
SemaDeclAttr.cpp
Go to the documentation of this file.
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
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Mangle.h"
24#include "clang/AST/Type.h"
26#include "clang/Basic/Cuda.h"
36#include "clang/Sema/Attr.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
42#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaARM.h"
46#include "clang/Sema/SemaAVR.h"
47#include "clang/Sema/SemaBPF.h"
48#include "clang/Sema/SemaCUDA.h"
49#include "clang/Sema/SemaHLSL.h"
51#include "clang/Sema/SemaM68k.h"
52#include "clang/Sema/SemaMIPS.h"
54#include "clang/Sema/SemaObjC.h"
58#include "clang/Sema/SemaSYCL.h"
60#include "clang/Sema/SemaWasm.h"
61#include "clang/Sema/SemaX86.h"
62#include "llvm/ADT/STLExtras.h"
63#include "llvm/ADT/STLForwardCompat.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Demangle/Demangle.h"
66#include "llvm/IR/Assumptions.h"
67#include "llvm/MC/MCSectionMachO.h"
68#include "llvm/Support/Error.h"
69#include "llvm/Support/MathExtras.h"
70#include "llvm/Support/raw_ostream.h"
71#include "llvm/TargetParser/Triple.h"
72#include <optional>
73
74using namespace clang;
75using namespace sema;
76
78 enum LANG {
81 ObjC
82 };
83} // end namespace AttributeLangSupport
84
85static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
86 // FIXME: Include the type in the argument list.
87 return AL.getNumArgs() + AL.hasParsedType();
88}
89
91
92/// Wrapper around checkUInt32Argument, with an extra check to be sure
93/// that the result will fit into a regular (signed) int. All args have the same
94/// purpose as they do in checkUInt32Argument.
95template <typename AttrInfo>
96static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
97 int &Val, unsigned Idx = UINT_MAX) {
98 uint32_t UVal;
99 if (!S.checkUInt32Argument(AI, Expr, UVal, Idx))
100 return false;
101
102 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
103 llvm::APSInt I(32); // for toString
104 I = UVal;
105 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
106 << toString(I, 10, false) << 32 << /* Unsigned */ 0;
107 return false;
108 }
109
110 Val = UVal;
111 return true;
112}
113
114/// Check if the argument \p E is a ASCII string literal. If not emit an error
115/// and return false, otherwise set \p Str to the value of the string literal
116/// and return true.
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/// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
135/// If not emit an error and return false. If the argument is an identifier it
136/// will emit an error with a fixit hint and treat it as if it was a string
137/// literal.
138bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
139 StringRef &Str,
140 SourceLocation *ArgLocation) {
141 // Look for identifiers. If we have one emit a hint to fix it to a literal.
142 if (AL.isArgIdent(ArgNum)) {
143 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
144 Diag(Loc->Loc, diag::err_attribute_argument_type)
145 << AL << AANT_ArgumentString
146 << FixItHint::CreateInsertion(Loc->Loc, "\"")
148 Str = Loc->Ident->getName();
149 if (ArgLocation)
150 *ArgLocation = Loc->Loc;
151 return true;
152 }
153
154 // Now check for an actual string literal.
155 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
156 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
157 if (ArgLocation)
158 *ArgLocation = ArgExpr->getBeginLoc();
159
160 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
161 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
162 << AL << AANT_ArgumentString;
163 return false;
164 }
165 Str = Literal->getString();
166 return checkStringLiteralArgumentAttr(AL, ArgExpr, Str, ArgLocation);
167}
168
169/// Check if the passed-in expression is of type int or bool.
170static bool isIntOrBool(Expr *Exp) {
171 QualType QT = Exp->getType();
172 return QT->isBooleanType() || QT->isIntegerType();
173}
174
175
176// Check to see if the type is a smart pointer of some kind. We assume
177// it's a smart pointer if it defines both operator-> and operator*.
179 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
183 return !Result.empty();
184 };
185
186 const RecordDecl *Record = RT->getDecl();
187 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
188 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
189 if (foundStarOperator && foundArrowOperator)
190 return true;
191
192 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
193 if (!CXXRecord)
194 return false;
195
196 for (const auto &BaseSpecifier : CXXRecord->bases()) {
197 if (!foundStarOperator)
198 foundStarOperator = IsOverloadedOperatorPresent(
199 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
200 if (!foundArrowOperator)
201 foundArrowOperator = IsOverloadedOperatorPresent(
202 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
203 }
204
205 if (foundStarOperator && foundArrowOperator)
206 return true;
207
208 return false;
209}
210
211/// Check if passed in Decl is a pointer type.
212/// Note that this function may produce an error message.
213/// \return true if the Decl is a pointer type; false otherwise
214static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
215 const ParsedAttr &AL) {
216 const auto *VD = cast<ValueDecl>(D);
217 QualType QT = VD->getType();
218 if (QT->isAnyPointerType())
219 return true;
220
221 if (const auto *RT = QT->getAs<RecordType>()) {
222 // If it's an incomplete type, it could be a smart pointer; skip it.
223 // (We don't want to force template instantiation if we can avoid it,
224 // since that would alter the order in which templates are instantiated.)
225 if (RT->isIncompleteType())
226 return true;
227
229 return true;
230 }
231
232 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
233 return false;
234}
235
236/// Checks that the passed in QualType either is of RecordType or points
237/// to RecordType. Returns the relevant RecordType, null if it does not exit.
239 if (const auto *RT = QT->getAs<RecordType>())
240 return RT;
241
242 // Now check if we point to record type.
243 if (const auto *PT = QT->getAs<PointerType>())
244 return PT->getPointeeType()->getAs<RecordType>();
245
246 return nullptr;
247}
248
249template <typename AttrType>
250static bool checkRecordDeclForAttr(const RecordDecl *RD) {
251 // Check if the record itself has the attribute.
252 if (RD->hasAttr<AttrType>())
253 return true;
254
255 // Else check if any base classes have the attribute.
256 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
257 if (!CRD->forallBases([](const CXXRecordDecl *Base) {
258 return !Base->hasAttr<AttrType>();
259 }))
260 return true;
261 }
262 return false;
263}
264
266 const RecordType *RT = getRecordType(Ty);
267
268 if (!RT)
269 return false;
270
271 // Don't check for the capability if the class hasn't been defined yet.
272 if (RT->isIncompleteType())
273 return true;
274
275 // Allow smart pointers to be used as capability objects.
276 // FIXME -- Check the type that the smart pointer points to.
278 return true;
279
280 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
281}
282
284 const auto *TD = Ty->getAs<TypedefType>();
285 if (!TD)
286 return false;
287
288 TypedefNameDecl *TN = TD->getDecl();
289 if (!TN)
290 return false;
291
292 return TN->hasAttr<CapabilityAttr>();
293}
294
295static bool typeHasCapability(Sema &S, QualType Ty) {
297 return true;
298
300 return true;
301
302 return false;
303}
304
305static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
306 // Capability expressions are simple expressions involving the boolean logic
307 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
308 // a DeclRefExpr is found, its type should be checked to determine whether it
309 // is a capability or not.
310
311 if (const auto *E = dyn_cast<CastExpr>(Ex))
312 return isCapabilityExpr(S, E->getSubExpr());
313 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
314 return isCapabilityExpr(S, E->getSubExpr());
315 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
316 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
317 E->getOpcode() == UO_Deref)
318 return isCapabilityExpr(S, E->getSubExpr());
319 return false;
320 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
321 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
322 return isCapabilityExpr(S, E->getLHS()) &&
323 isCapabilityExpr(S, E->getRHS());
324 return false;
325 }
326
327 return typeHasCapability(S, Ex->getType());
328}
329
330/// Checks that all attribute arguments, starting from Sidx, resolve to
331/// a capability object.
332/// \param Sidx The attribute argument index to start checking with.
333/// \param ParamIdxOk Whether an argument can be indexing into a function
334/// parameter list.
336 const ParsedAttr &AL,
338 unsigned Sidx = 0,
339 bool ParamIdxOk = false) {
340 if (Sidx == AL.getNumArgs()) {
341 // If we don't have any capability arguments, the attribute implicitly
342 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
343 // a non-static method, and that the class is a (scoped) capability.
344 const auto *MD = dyn_cast<const CXXMethodDecl>(D);
345 if (MD && !MD->isStatic()) {
346 const CXXRecordDecl *RD = MD->getParent();
347 // FIXME -- need to check this again on template instantiation
348 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
349 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
350 S.Diag(AL.getLoc(),
351 diag::warn_thread_attribute_not_on_capability_member)
352 << AL << MD->getParent();
353 } else {
354 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
355 << AL;
356 }
357 }
358
359 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
360 Expr *ArgExp = AL.getArgAsExpr(Idx);
361
362 if (ArgExp->isTypeDependent()) {
363 // FIXME -- need to check this again on template instantiation
364 Args.push_back(ArgExp);
365 continue;
366 }
367
368 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
369 if (StrLit->getLength() == 0 ||
370 (StrLit->isOrdinary() && StrLit->getString() == "*")) {
371 // Pass empty strings to the analyzer without warnings.
372 // Treat "*" as the universal lock.
373 Args.push_back(ArgExp);
374 continue;
375 }
376
377 // We allow constant strings to be used as a placeholder for expressions
378 // that are not valid C++ syntax, but warn that they are ignored.
379 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
380 Args.push_back(ArgExp);
381 continue;
382 }
383
384 QualType ArgTy = ArgExp->getType();
385
386 // A pointer to member expression of the form &MyClass::mu is treated
387 // specially -- we need to look at the type of the member.
388 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
389 if (UOp->getOpcode() == UO_AddrOf)
390 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
391 if (DRE->getDecl()->isCXXInstanceMember())
392 ArgTy = DRE->getDecl()->getType();
393
394 // First see if we can just cast to record type, or pointer to record type.
395 const RecordType *RT = getRecordType(ArgTy);
396
397 // Now check if we index into a record type function param.
398 if(!RT && ParamIdxOk) {
399 const auto *FD = dyn_cast<FunctionDecl>(D);
400 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
401 if(FD && IL) {
402 unsigned int NumParams = FD->getNumParams();
403 llvm::APInt ArgValue = IL->getValue();
404 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
405 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
406 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
407 S.Diag(AL.getLoc(),
408 diag::err_attribute_argument_out_of_bounds_extra_info)
409 << AL << Idx + 1 << NumParams;
410 continue;
411 }
412 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
413 }
414 }
415
416 // If the type does not have a capability, see if the components of the
417 // expression have capabilities. This allows for writing C code where the
418 // capability may be on the type, and the expression is a capability
419 // boolean logic expression. Eg) requires_capability(A || B && !C)
420 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
421 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
422 << AL << ArgTy;
423
424 Args.push_back(ArgExp);
425 }
426}
427
428//===----------------------------------------------------------------------===//
429// Attribute Implementations
430//===----------------------------------------------------------------------===//
431
432static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
433 if (!threadSafetyCheckIsPointer(S, D, AL))
434 return;
435
436 D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
437}
438
439static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
440 Expr *&Arg) {
442 // check that all arguments are lockable objects
443 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
444 unsigned Size = Args.size();
445 if (Size != 1)
446 return false;
447
448 Arg = Args[0];
449
450 return true;
451}
452
453static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
454 Expr *Arg = nullptr;
455 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
456 return;
457
458 D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
459}
460
461static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
462 Expr *Arg = nullptr;
463 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
464 return;
465
466 if (!threadSafetyCheckIsPointer(S, D, AL))
467 return;
468
469 D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
470}
471
472static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
474 if (!AL.checkAtLeastNumArgs(S, 1))
475 return false;
476
477 // Check that this attribute only applies to lockable types.
478 QualType QT = cast<ValueDecl>(D)->getType();
479 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
480 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
481 return false;
482 }
483
484 // Check that all arguments are lockable objects.
485 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
486 if (Args.empty())
487 return false;
488
489 return true;
490}
491
492static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
494 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
495 return;
496
497 Expr **StartArg = &Args[0];
498 D->addAttr(::new (S.Context)
499 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
500}
501
502static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
504 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
505 return;
506
507 Expr **StartArg = &Args[0];
508 D->addAttr(::new (S.Context)
509 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
510}
511
512static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
514 // zero or more arguments ok
515 // check that all arguments are lockable objects
516 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
517
518 return true;
519}
520
521static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
523 if (!checkLockFunAttrCommon(S, D, AL, Args))
524 return;
525
526 unsigned Size = Args.size();
527 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
528 D->addAttr(::new (S.Context)
529 AssertSharedLockAttr(S.Context, AL, StartArg, Size));
530}
531
533 const ParsedAttr &AL) {
535 if (!checkLockFunAttrCommon(S, D, AL, Args))
536 return;
537
538 unsigned Size = Args.size();
539 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
540 D->addAttr(::new (S.Context)
541 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
542}
543
544/// Checks to be sure that the given parameter number is in bounds, and
545/// is an integral type. Will emit appropriate diagnostics if this returns
546/// false.
547///
548/// AttrArgNo is used to actually retrieve the argument, so it's base-0.
549template <typename AttrInfo>
550static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
551 unsigned AttrArgNo) {
552 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
553 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
554 ParamIdx Idx;
555 if (!S.checkFunctionOrMethodParameterIndex(D, AI, AttrArgNo + 1, AttrArg,
556 Idx))
557 return false;
558
560 if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
561 SourceLocation SrcLoc = AttrArg->getBeginLoc();
562 S.Diag(SrcLoc, diag::err_attribute_integers_only)
564 return false;
565 }
566 return true;
567}
568
569static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
570 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
571 return;
572
574
576 if (!RetTy->isPointerType()) {
577 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
578 return;
579 }
580
581 const Expr *SizeExpr = AL.getArgAsExpr(0);
582 int SizeArgNoVal;
583 // Parameter indices are 1-indexed, hence Index=1
584 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
585 return;
586 if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
587 return;
588 ParamIdx SizeArgNo(SizeArgNoVal, D);
589
590 ParamIdx NumberArgNo;
591 if (AL.getNumArgs() == 2) {
592 const Expr *NumberExpr = AL.getArgAsExpr(1);
593 int Val;
594 // Parameter indices are 1-based, hence Index=2
595 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
596 return;
597 if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
598 return;
599 NumberArgNo = ParamIdx(Val, D);
600 }
601
602 D->addAttr(::new (S.Context)
603 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
604}
605
606static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
608 if (!AL.checkAtLeastNumArgs(S, 1))
609 return false;
610
611 if (!isIntOrBool(AL.getArgAsExpr(0))) {
612 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
613 << AL << 1 << AANT_ArgumentIntOrBool;
614 return false;
615 }
616
617 // check that all arguments are lockable objects
618 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
619
620 return true;
621}
622
624 const ParsedAttr &AL) {
626 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
627 return;
628
629 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
630 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
631}
632
634 const ParsedAttr &AL) {
636 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
637 return;
638
639 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
640 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
641}
642
643static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
644 // check that the argument is lockable object
646 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
647 unsigned Size = Args.size();
648 if (Size == 0)
649 return;
650
651 D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
652}
653
654static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
655 if (!AL.checkAtLeastNumArgs(S, 1))
656 return;
657
658 // check that all arguments are lockable objects
660 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
661 unsigned Size = Args.size();
662 if (Size == 0)
663 return;
664 Expr **StartArg = &Args[0];
665
666 D->addAttr(::new (S.Context)
667 LocksExcludedAttr(S.Context, AL, StartArg, Size));
668}
669
670static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
671 Expr *&Cond, StringRef &Msg) {
672 Cond = AL.getArgAsExpr(0);
673 if (!Cond->isTypeDependent()) {
675 if (Converted.isInvalid())
676 return false;
677 Cond = Converted.get();
678 }
679
680 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
681 return false;
682
683 if (Msg.empty())
684 Msg = "<no message provided>";
685
687 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
688 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
689 Diags)) {
690 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
691 for (const PartialDiagnosticAt &PDiag : Diags)
692 S.Diag(PDiag.first, PDiag.second);
693 return false;
694 }
695 return true;
696}
697
698static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
699 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
700
701 Expr *Cond;
702 StringRef Msg;
703 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
704 D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
705}
706
707static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
708 StringRef NewUserDiagnostic;
709 if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic))
710 return;
711 if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
712 D->addAttr(EA);
713}
714
716 const ParsedAttr &AL) {
717 const auto *PD = isa<CXXRecordDecl>(D)
718 ? cast<DeclContext>(D)
720 if (const auto *RD = dyn_cast<CXXRecordDecl>(PD); RD && RD->isLocalClass()) {
721 S.Diag(AL.getLoc(),
722 diag::warn_attribute_exclude_from_explicit_instantiation_local_class)
723 << AL << /*IsMember=*/!isa<CXXRecordDecl>(D);
724 return;
725 }
726 D->addAttr(::new (S.Context)
727 ExcludeFromExplicitInstantiationAttr(S.Context, AL));
728}
729
730namespace {
731/// Determines if a given Expr references any of the given function's
732/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
733class ArgumentDependenceChecker
734 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
735#ifndef NDEBUG
736 const CXXRecordDecl *ClassType;
737#endif
739 bool Result;
740
741public:
742 ArgumentDependenceChecker(const FunctionDecl *FD) {
743#ifndef NDEBUG
744 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
745 ClassType = MD->getParent();
746 else
747 ClassType = nullptr;
748#endif
749 Parms.insert(FD->param_begin(), FD->param_end());
750 }
751
752 bool referencesArgs(Expr *E) {
753 Result = false;
754 TraverseStmt(E);
755 return Result;
756 }
757
758 bool VisitCXXThisExpr(CXXThisExpr *E) {
759 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
760 "`this` doesn't refer to the enclosing class?");
761 Result = true;
762 return false;
763 }
764
765 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
766 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
767 if (Parms.count(PVD)) {
768 Result = true;
769 return false;
770 }
771 return true;
772 }
773};
774}
775
777 const ParsedAttr &AL) {
778 const auto *DeclFD = cast<FunctionDecl>(D);
779
780 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclFD))
781 if (!MethodDecl->isStatic()) {
782 S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL;
783 return;
784 }
785
786 auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
787 SourceLocation Loc = [&]() {
788 auto Union = AL.getArg(Index - 1);
789 if (Union.is<Expr *>())
790 return Union.get<Expr *>()->getBeginLoc();
791 return Union.get<IdentifierLoc *>()->Loc;
792 }();
793
794 S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T;
795 };
796
797 FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
798 if (!AL.isArgExpr(0))
799 return nullptr;
800 auto *F = dyn_cast_if_present<DeclRefExpr>(AL.getArgAsExpr(0));
801 if (!F)
802 return nullptr;
803 return dyn_cast_if_present<FunctionDecl>(F->getFoundDecl());
804 }();
805
806 if (!AttrFD || !AttrFD->getBuiltinID(true)) {
807 DiagnoseType(1, AANT_ArgumentBuiltinFunction);
808 return;
809 }
810
811 if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
812 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for)
813 << AL << AttrFD << AttrFD->getNumParams();
814 return;
815 }
816
818
819 for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
820 if (!AL.isArgExpr(I)) {
821 DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
822 return;
823 }
824
825 const Expr *IndexExpr = AL.getArgAsExpr(I);
826 uint32_t Index;
827
828 if (!S.checkUInt32Argument(AL, IndexExpr, Index, I + 1, false))
829 return;
830
831 if (Index > DeclFD->getNumParams()) {
832 S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function)
833 << AL << Index << DeclFD << DeclFD->getNumParams();
834 return;
835 }
836
837 QualType T1 = AttrFD->getParamDecl(I - 1)->getType();
838 QualType T2 = DeclFD->getParamDecl(Index - 1)->getType();
839
842 S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types)
843 << AL << Index << DeclFD << T2 << I << AttrFD << T1;
844 return;
845 }
846
847 Indices.push_back(Index - 1);
848 }
849
850 D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr(
851 S.Context, AL, AttrFD, Indices.data(), Indices.size()));
852}
853
854static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
855 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
856
857 Expr *Cond;
858 StringRef Msg;
859 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
860 return;
861
862 StringRef DiagTypeStr;
863 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
864 return;
865
866 DiagnoseIfAttr::DiagnosticType DiagType;
867 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
868 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
869 diag::err_diagnose_if_invalid_diagnostic_type);
870 return;
871 }
872
873 bool ArgDependent = false;
874 if (const auto *FD = dyn_cast<FunctionDecl>(D))
875 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
876 D->addAttr(::new (S.Context) DiagnoseIfAttr(
877 S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
878}
879
880static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
881 static constexpr const StringRef kWildcard = "*";
882
884 bool HasWildcard = false;
885
886 const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
887 if (Name == kWildcard)
888 HasWildcard = true;
889 Names.push_back(Name);
890 };
891
892 // Add previously defined attributes.
893 if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
894 for (StringRef BuiltinName : NBA->builtinNames())
895 AddBuiltinName(BuiltinName);
896
897 // Add current attributes.
898 if (AL.getNumArgs() == 0)
899 AddBuiltinName(kWildcard);
900 else
901 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
902 StringRef BuiltinName;
903 SourceLocation LiteralLoc;
904 if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
905 return;
906
907 if (Builtin::Context::isBuiltinFunc(BuiltinName))
908 AddBuiltinName(BuiltinName);
909 else
910 S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
911 << BuiltinName << AL;
912 }
913
914 // Repeating the same attribute is fine.
915 llvm::sort(Names);
916 Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
917
918 // Empty no_builtin must be on its own.
919 if (HasWildcard && Names.size() > 1)
920 S.Diag(D->getLocation(),
921 diag::err_attribute_no_builtin_wildcard_or_builtin_name)
922 << AL;
923
924 if (D->hasAttr<NoBuiltinAttr>())
925 D->dropAttr<NoBuiltinAttr>();
926 D->addAttr(::new (S.Context)
927 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
928}
929
930static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
931 if (D->hasAttr<PassObjectSizeAttr>()) {
932 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
933 return;
934 }
935
936 Expr *E = AL.getArgAsExpr(0);
937 uint32_t Type;
938 if (!S.checkUInt32Argument(AL, E, Type, /*Idx=*/1))
939 return;
940
941 // pass_object_size's argument is passed in as the second argument of
942 // __builtin_object_size. So, it has the same constraints as that second
943 // argument; namely, it must be in the range [0, 3].
944 if (Type > 3) {
945 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
946 << AL << 0 << 3 << E->getSourceRange();
947 return;
948 }
949
950 // pass_object_size is only supported on constant pointer parameters; as a
951 // kindness to users, we allow the parameter to be non-const for declarations.
952 // At this point, we have no clue if `D` belongs to a function declaration or
953 // definition, so we defer the constness check until later.
954 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
955 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
956 return;
957 }
958
959 D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
960}
961
962static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
963 ConsumableAttr::ConsumedState DefaultState;
964
965 if (AL.isArgIdent(0)) {
966 IdentifierLoc *IL = AL.getArgAsIdent(0);
967 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
968 DefaultState)) {
969 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
970 << IL->Ident;
971 return;
972 }
973 } else {
974 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
976 return;
977 }
978
979 D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
980}
981
983 const ParsedAttr &AL) {
985
986 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
987 if (!RD->hasAttr<ConsumableAttr>()) {
988 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
989
990 return false;
991 }
992 }
993
994 return true;
995}
996
997static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
998 if (!AL.checkAtLeastNumArgs(S, 1))
999 return;
1000
1001 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1002 return;
1003
1005 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1006 CallableWhenAttr::ConsumedState CallableState;
1007
1008 StringRef StateString;
1010 if (AL.isArgIdent(ArgIndex)) {
1011 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1012 StateString = Ident->Ident->getName();
1013 Loc = Ident->Loc;
1014 } else {
1015 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1016 return;
1017 }
1018
1019 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1020 CallableState)) {
1021 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1022 return;
1023 }
1024
1025 States.push_back(CallableState);
1026 }
1027
1028 D->addAttr(::new (S.Context)
1029 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1030}
1031
1032static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1033 ParamTypestateAttr::ConsumedState ParamState;
1034
1035 if (AL.isArgIdent(0)) {
1036 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1037 StringRef StateString = Ident->Ident->getName();
1038
1039 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1040 ParamState)) {
1041 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1042 << AL << StateString;
1043 return;
1044 }
1045 } else {
1046 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1047 << AL << AANT_ArgumentIdentifier;
1048 return;
1049 }
1050
1051 // FIXME: This check is currently being done in the analysis. It can be
1052 // enabled here only after the parser propagates attributes at
1053 // template specialization definition, not declaration.
1054 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1055 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1056 //
1057 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1058 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1059 // ReturnType.getAsString();
1060 // return;
1061 //}
1062
1063 D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1064}
1065
1066static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1067 ReturnTypestateAttr::ConsumedState ReturnState;
1068
1069 if (AL.isArgIdent(0)) {
1070 IdentifierLoc *IL = AL.getArgAsIdent(0);
1071 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1072 ReturnState)) {
1073 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1074 << IL->Ident;
1075 return;
1076 }
1077 } else {
1078 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1079 << AL << AANT_ArgumentIdentifier;
1080 return;
1081 }
1082
1083 // FIXME: This check is currently being done in the analysis. It can be
1084 // enabled here only after the parser propagates attributes at
1085 // template specialization definition, not declaration.
1086 // QualType ReturnType;
1087 //
1088 // if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1089 // ReturnType = Param->getType();
1090 //
1091 //} else if (const CXXConstructorDecl *Constructor =
1092 // dyn_cast<CXXConstructorDecl>(D)) {
1093 // ReturnType = Constructor->getFunctionObjectParameterType();
1094 //
1095 //} else {
1096 //
1097 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1098 //}
1099 //
1100 // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1101 //
1102 // if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1103 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1104 // ReturnType.getAsString();
1105 // return;
1106 //}
1107
1108 D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1109}
1110
1111static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1112 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1113 return;
1114
1115 SetTypestateAttr::ConsumedState NewState;
1116 if (AL.isArgIdent(0)) {
1117 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1118 StringRef Param = Ident->Ident->getName();
1119 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1120 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1121 << Param;
1122 return;
1123 }
1124 } else {
1125 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1126 << AL << AANT_ArgumentIdentifier;
1127 return;
1128 }
1129
1130 D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1131}
1132
1133static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1134 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1135 return;
1136
1137 TestTypestateAttr::ConsumedState TestState;
1138 if (AL.isArgIdent(0)) {
1139 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1140 StringRef Param = Ident->Ident->getName();
1141 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1142 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1143 << Param;
1144 return;
1145 }
1146 } else {
1147 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1148 << AL << AANT_ArgumentIdentifier;
1149 return;
1150 }
1151
1152 D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1153}
1154
1155static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1156 // Remember this typedef decl, we will need it later for diagnostics.
1157 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1158}
1159
1160static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1161 if (auto *TD = dyn_cast<TagDecl>(D))
1162 TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1163 else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1164 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1165 !FD->getType()->isIncompleteType() &&
1166 FD->isBitField() &&
1167 S.Context.getTypeAlign(FD->getType()) <= 8);
1168
1169 if (S.getASTContext().getTargetInfo().getTriple().isPS()) {
1170 if (BitfieldByteAligned)
1171 // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1172 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1173 << AL << FD->getType();
1174 else
1175 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1176 } else {
1177 // Report warning about changed offset in the newer compiler versions.
1178 if (BitfieldByteAligned)
1179 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1180
1181 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1182 }
1183
1184 } else
1185 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1186}
1187
1188static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1189 auto *RD = cast<CXXRecordDecl>(D);
1190 ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1191 assert(CTD && "attribute does not appertain to this declaration");
1192
1193 ParsedType PT = AL.getTypeArg();
1194 TypeSourceInfo *TSI = nullptr;
1195 QualType T = S.GetTypeFromParser(PT, &TSI);
1196 if (!TSI)
1198
1199 if (!T.hasQualifiers() && T->isTypedefNameType()) {
1200 // Find the template name, if this type names a template specialization.
1201 const TemplateDecl *Template = nullptr;
1202 if (const auto *CTSD = dyn_cast_if_present<ClassTemplateSpecializationDecl>(
1203 T->getAsCXXRecordDecl())) {
1204 Template = CTSD->getSpecializedTemplate();
1205 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1206 while (TST && TST->isTypeAlias())
1207 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1208 if (TST)
1209 Template = TST->getTemplateName().getAsTemplateDecl();
1210 }
1211
1212 if (Template && declaresSameEntity(Template, CTD)) {
1213 D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1214 return;
1215 }
1216 }
1217
1218 S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1219 << T << CTD;
1220 if (const auto *TT = T->getAs<TypedefType>())
1221 S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1222 << TT->getDecl();
1223}
1224
1226 if (RefOkay) {
1227 if (T->isReferenceType())
1228 return true;
1229 } else {
1230 T = T.getNonReferenceType();
1231 }
1232
1233 // The nonnull attribute, and other similar attributes, can be applied to a
1234 // transparent union that contains a pointer type.
1235 if (const RecordType *UT = T->getAsUnionType()) {
1236 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1237 RecordDecl *UD = UT->getDecl();
1238 for (const auto *I : UD->fields()) {
1239 QualType QT = I->getType();
1240 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1241 return true;
1242 }
1243 }
1244 }
1245
1246 return T->isAnyPointerType() || T->isBlockPointerType();
1247}
1248
1249static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1250 SourceRange AttrParmRange,
1251 SourceRange TypeRange,
1252 bool isReturnValue = false) {
1253 if (!S.isValidPointerAttrType(T)) {
1254 if (isReturnValue)
1255 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1256 << AL << AttrParmRange << TypeRange;
1257 else
1258 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1259 << AL << AttrParmRange << TypeRange << 0;
1260 return false;
1261 }
1262 return true;
1263}
1264
1265static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1266 SmallVector<ParamIdx, 8> NonNullArgs;
1267 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1268 Expr *Ex = AL.getArgAsExpr(I);
1269 ParamIdx Idx;
1270 if (!S.checkFunctionOrMethodParameterIndex(D, AL, I + 1, Ex, Idx))
1271 return;
1272
1273 // Is the function argument a pointer type?
1277 Ex->getSourceRange(),
1279 continue;
1280
1281 NonNullArgs.push_back(Idx);
1282 }
1283
1284 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1285 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1286 // check if the attribute came from a macro expansion or a template
1287 // instantiation.
1288 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1290 bool AnyPointers = isFunctionOrMethodVariadic(D);
1291 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1292 I != E && !AnyPointers; ++I) {
1295 AnyPointers = true;
1296 }
1297
1298 if (!AnyPointers)
1299 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1300 }
1301
1302 ParamIdx *Start = NonNullArgs.data();
1303 unsigned Size = NonNullArgs.size();
1304 llvm::array_pod_sort(Start, Start + Size);
1305 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1306}
1307
1309 const ParsedAttr &AL) {
1310 if (AL.getNumArgs() > 0) {
1311 if (D->getFunctionType()) {
1312 handleNonNullAttr(S, D, AL);
1313 } else {
1314 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1315 << D->getSourceRange();
1316 }
1317 return;
1318 }
1319
1320 // Is the argument a pointer type?
1321 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1322 D->getSourceRange()))
1323 return;
1324
1325 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1326}
1327
1328static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1331 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1332 /* isReturnValue */ true))
1333 return;
1334
1335 D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1336}
1337
1338static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1339 if (D->isInvalidDecl())
1340 return;
1341
1342 // noescape only applies to pointer types.
1343 QualType T = cast<ParmVarDecl>(D)->getType();
1344 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1345 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1346 << AL << AL.getRange() << 0;
1347 return;
1348 }
1349
1350 D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1351}
1352
1353static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1354 Expr *E = AL.getArgAsExpr(0),
1355 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1356 S.AddAssumeAlignedAttr(D, AL, E, OE);
1357}
1358
1359static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1360 S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1361}
1362
1364 Expr *OE) {
1367
1368 AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1369 SourceLocation AttrLoc = TmpAttr.getLocation();
1370
1371 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1372 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1373 << &TmpAttr << TmpAttr.getRange() << SR;
1374 return;
1375 }
1376
1377 if (!E->isValueDependent()) {
1378 std::optional<llvm::APSInt> I = llvm::APSInt(64);
1379 if (!(I = E->getIntegerConstantExpr(Context))) {
1380 if (OE)
1381 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1382 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1383 << E->getSourceRange();
1384 else
1385 Diag(AttrLoc, diag::err_attribute_argument_type)
1386 << &TmpAttr << AANT_ArgumentIntegerConstant
1387 << E->getSourceRange();
1388 return;
1389 }
1390
1391 if (!I->isPowerOf2()) {
1392 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1393 << E->getSourceRange();
1394 return;
1395 }
1396
1397 if (*I > Sema::MaximumAlignment)
1398 Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1400 }
1401
1402 if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
1403 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1404 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1405 << OE->getSourceRange();
1406 return;
1407 }
1408
1409 D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1410}
1411
1413 Expr *ParamExpr) {
1415
1416 AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1417 SourceLocation AttrLoc = CI.getLoc();
1418
1419 if (!ResultType->isDependentType() &&
1420 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1421 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1422 << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1423 return;
1424 }
1425
1426 ParamIdx Idx;
1427 const auto *FuncDecl = cast<FunctionDecl>(D);
1428 if (!checkFunctionOrMethodParameterIndex(FuncDecl, TmpAttr,
1429 /*AttrArgNum=*/1, ParamExpr, Idx))
1430 return;
1431
1433 if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1434 !Ty->isAlignValT()) {
1435 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1436 << &TmpAttr
1437 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1438 return;
1439 }
1440
1441 D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1442}
1443
1444/// Normalize the attribute, __foo__ becomes foo.
1445/// Returns true if normalization was applied.
1446static bool normalizeName(StringRef &AttrName) {
1447 if (AttrName.size() > 4 && AttrName.starts_with("__") &&
1448 AttrName.ends_with("__")) {
1449 AttrName = AttrName.drop_front(2).drop_back(2);
1450 return true;
1451 }
1452 return false;
1453}
1454
1455static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1456 // This attribute must be applied to a function declaration. The first
1457 // argument to the attribute must be an identifier, the name of the resource,
1458 // for example: malloc. The following arguments must be argument indexes, the
1459 // arguments must be of integer type for Returns, otherwise of pointer type.
1460 // The difference between Holds and Takes is that a pointer may still be used
1461 // after being held. free() should be __attribute((ownership_takes)), whereas
1462 // a list append function may well be __attribute((ownership_holds)).
1463
1464 if (!AL.isArgIdent(0)) {
1465 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1466 << AL << 1 << AANT_ArgumentIdentifier;
1467 return;
1468 }
1469
1470 // Figure out our Kind.
1471 OwnershipAttr::OwnershipKind K =
1472 OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1473
1474 // Check arguments.
1475 switch (K) {
1476 case OwnershipAttr::Takes:
1477 case OwnershipAttr::Holds:
1478 if (AL.getNumArgs() < 2) {
1479 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1480 return;
1481 }
1482 break;
1483 case OwnershipAttr::Returns:
1484 if (AL.getNumArgs() > 2) {
1485 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1486 return;
1487 }
1488 break;
1489 }
1490
1492
1493 StringRef ModuleName = Module->getName();
1494 if (normalizeName(ModuleName)) {
1495 Module = &S.PP.getIdentifierTable().get(ModuleName);
1496 }
1497
1498 SmallVector<ParamIdx, 8> OwnershipArgs;
1499 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1500 Expr *Ex = AL.getArgAsExpr(i);
1501 ParamIdx Idx;
1502 if (!S.checkFunctionOrMethodParameterIndex(D, AL, i, Ex, Idx))
1503 return;
1504
1505 // Is the function argument a pointer type?
1507 int Err = -1; // No error
1508 switch (K) {
1509 case OwnershipAttr::Takes:
1510 case OwnershipAttr::Holds:
1511 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1512 Err = 0;
1513 break;
1514 case OwnershipAttr::Returns:
1515 if (!T->isIntegerType())
1516 Err = 1;
1517 break;
1518 }
1519 if (-1 != Err) {
1520 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1521 << Ex->getSourceRange();
1522 return;
1523 }
1524
1525 // Check we don't have a conflict with another ownership attribute.
1526 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1527 // Cannot have two ownership attributes of different kinds for the same
1528 // index.
1529 if (I->getOwnKind() != K && llvm::is_contained(I->args(), Idx)) {
1530 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1531 << AL << I
1532 << (AL.isRegularKeywordAttribute() ||
1533 I->isRegularKeywordAttribute());
1534 return;
1535 } else if (K == OwnershipAttr::Returns &&
1536 I->getOwnKind() == OwnershipAttr::Returns) {
1537 // A returns attribute conflicts with any other returns attribute using
1538 // a different index.
1539 if (!llvm::is_contained(I->args(), Idx)) {
1540 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1541 << I->args_begin()->getSourceIndex();
1542 if (I->args_size())
1543 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1544 << Idx.getSourceIndex() << Ex->getSourceRange();
1545 return;
1546 }
1547 }
1548 }
1549 OwnershipArgs.push_back(Idx);
1550 }
1551
1552 ParamIdx *Start = OwnershipArgs.data();
1553 unsigned Size = OwnershipArgs.size();
1554 llvm::array_pod_sort(Start, Start + Size);
1555 D->addAttr(::new (S.Context)
1556 OwnershipAttr(S.Context, AL, Module, Start, Size));
1557}
1558
1559static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1560 // Check the attribute arguments.
1561 if (AL.getNumArgs() > 1) {
1562 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1563 return;
1564 }
1565
1566 // gcc rejects
1567 // class c {
1568 // static int a __attribute__((weakref ("v2")));
1569 // static int b() __attribute__((weakref ("f3")));
1570 // };
1571 // and ignores the attributes of
1572 // void f(void) {
1573 // static int a __attribute__((weakref ("v2")));
1574 // }
1575 // we reject them
1576 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1577 if (!Ctx->isFileContext()) {
1578 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1579 << cast<NamedDecl>(D);
1580 return;
1581 }
1582
1583 // The GCC manual says
1584 //
1585 // At present, a declaration to which `weakref' is attached can only
1586 // be `static'.
1587 //
1588 // It also says
1589 //
1590 // Without a TARGET,
1591 // given as an argument to `weakref' or to `alias', `weakref' is
1592 // equivalent to `weak'.
1593 //
1594 // gcc 4.4.1 will accept
1595 // int a7 __attribute__((weakref));
1596 // as
1597 // int a7 __attribute__((weak));
1598 // This looks like a bug in gcc. We reject that for now. We should revisit
1599 // it if this behaviour is actually used.
1600
1601 // GCC rejects
1602 // static ((alias ("y"), weakref)).
1603 // Should we? How to check that weakref is before or after alias?
1604
1605 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1606 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1607 // StringRef parameter it was given anyway.
1608 StringRef Str;
1609 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1610 // GCC will accept anything as the argument of weakref. Should we
1611 // check for an existing decl?
1612 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1613
1614 D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1615}
1616
1617// Mark alias/ifunc target as used. Due to name mangling, we look up the
1618// demangled name ignoring parameters (not supported by microsoftDemangle
1619// https://github.com/llvm/llvm-project/issues/88825). This should handle the
1620// majority of use cases while leaving namespace scope names unmarked.
1621static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
1622 StringRef Str) {
1623 std::unique_ptr<char, llvm::FreeDeleter> Demangled;
1624 if (S.getASTContext().getCXXABIKind() != TargetCXXABI::Microsoft)
1625 Demangled.reset(llvm::itaniumDemangle(Str, /*ParseParams=*/false));
1626 std::unique_ptr<MangleContext> MC(S.Context.createMangleContext());
1627 SmallString<256> Name;
1628
1630 &S.Context.Idents.get(Demangled ? Demangled.get() : Str), AL.getLoc());
1632 if (S.LookupName(LR, S.TUScope)) {
1633 for (NamedDecl *ND : LR) {
1634 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND))
1635 continue;
1636 if (MC->shouldMangleDeclName(ND)) {
1637 llvm::raw_svector_ostream Out(Name);
1638 Name.clear();
1639 MC->mangleName(GlobalDecl(ND), Out);
1640 } else {
1641 Name = ND->getIdentifier()->getName();
1642 }
1643 if (Name == Str)
1644 ND->markUsed(S.Context);
1645 }
1646 }
1647}
1648
1649static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1650 StringRef Str;
1651 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1652 return;
1653
1654 // Aliases should be on declarations, not definitions.
1655 const auto *FD = cast<FunctionDecl>(D);
1656 if (FD->isThisDeclarationADefinition()) {
1657 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1658 return;
1659 }
1660
1661 markUsedForAliasOrIfunc(S, D, AL, Str);
1662 D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1663}
1664
1665static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1666 StringRef Str;
1667 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1668 return;
1669
1670 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1671 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1672 return;
1673 }
1674
1675 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1676 CudaVersion Version =
1678 if (Version != CudaVersion::UNKNOWN && Version < CudaVersion::CUDA_100)
1679 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1680 }
1681
1682 // Aliases should be on declarations, not definitions.
1683 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1684 if (FD->isThisDeclarationADefinition()) {
1685 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1686 return;
1687 }
1688 } else {
1689 const auto *VD = cast<VarDecl>(D);
1690 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1691 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1692 return;
1693 }
1694 }
1695
1696 markUsedForAliasOrIfunc(S, D, AL, Str);
1697 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1698}
1699
1700static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1701 StringRef Model;
1702 SourceLocation LiteralLoc;
1703 // Check that it is a string.
1704 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1705 return;
1706
1707 // Check that the value.
1708 if (Model != "global-dynamic" && Model != "local-dynamic"
1709 && Model != "initial-exec" && Model != "local-exec") {
1710 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1711 return;
1712 }
1713
1714 D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
1715}
1716
1717static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1719 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1720 D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
1721 return;
1722 }
1723
1724 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1726}
1727
1728static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1729 // Ensure we don't combine these with themselves, since that causes some
1730 // confusing behavior.
1731 if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
1732 if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
1733 return;
1734
1735 if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
1736 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
1737 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
1738 return;
1739 }
1740 } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
1741 if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
1742 return;
1743
1744 if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
1745 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
1746 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
1747 return;
1748 }
1749 }
1750
1751 FunctionDecl *FD = cast<FunctionDecl>(D);
1752
1753 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1754 if (MD->getParent()->isLambda()) {
1755 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1756 return;
1757 }
1758 }
1759
1760 if (!AL.checkAtLeastNumArgs(S, 1))
1761 return;
1762
1764 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1765 if (!AL.isArgIdent(ArgNo)) {
1766 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1767 << AL << AANT_ArgumentIdentifier;
1768 return;
1769 }
1770
1771 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1772 StringRef CPUName = CPUArg->Ident->getName().trim();
1773
1775 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1776 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1777 return;
1778 }
1779
1781 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1782 return Target.CPUSpecificManglingCharacter(CPUName) ==
1783 Target.CPUSpecificManglingCharacter(Cur->getName());
1784 })) {
1785 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1786 return;
1787 }
1788 CPUs.push_back(CPUArg->Ident);
1789 }
1790
1791 FD->setIsMultiVersion(true);
1792 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
1793 D->addAttr(::new (S.Context)
1794 CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
1795 else
1796 D->addAttr(::new (S.Context)
1797 CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
1798}
1799
1800static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1801 if (S.LangOpts.CPlusPlus) {
1802 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
1804 return;
1805 }
1806
1807 D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
1808}
1809
1810static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1811 if (AL.isDeclspecAttribute()) {
1812 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1813 const auto &Arch = Triple.getArch();
1814 if (Arch != llvm::Triple::x86 &&
1815 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1816 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
1817 << AL << Triple.getArchName();
1818 return;
1819 }
1820
1821 // This form is not allowed to be written on a member function (static or
1822 // nonstatic) when in Microsoft compatibility mode.
1823 if (S.getLangOpts().MSVCCompat && isa<CXXMethodDecl>(D)) {
1824 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
1825 << AL << AL.isRegularKeywordAttribute() << "non-member functions";
1826 return;
1827 }
1828 }
1829
1830 D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
1831}
1832
1833static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
1834 if (hasDeclarator(D)) return;
1835
1836 if (!isa<ObjCMethodDecl>(D)) {
1837 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
1838 << Attrs << Attrs.isRegularKeywordAttribute()
1840 return;
1841 }
1842
1843 D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
1844}
1845
1846static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) {
1847 // The [[_Noreturn]] spelling is deprecated in C23, so if that was used,
1848 // issue an appropriate diagnostic. However, don't issue a diagnostic if the
1849 // attribute name comes from a macro expansion. We don't want to punish users
1850 // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
1851 // is defined as a macro which expands to '_Noreturn').
1852 if (!S.getLangOpts().CPlusPlus &&
1853 A.getSemanticSpelling() == CXX11NoReturnAttr::C23_Noreturn &&
1854 !(A.getLoc().isMacroID() &&
1856 S.Diag(A.getLoc(), diag::warn_deprecated_noreturn_spelling) << A.getRange();
1857
1858 D->addAttr(::new (S.Context) CXX11NoReturnAttr(S.Context, A));
1859}
1860
1861static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
1862 if (!S.getLangOpts().CFProtectionBranch)
1863 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
1864 else
1865 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
1866}
1867
1869 if (!Attrs.checkExactlyNumArgs(*this, 0)) {
1870 Attrs.setInvalid();
1871 return true;
1872 }
1873
1874 return false;
1875}
1876
1878 // Check whether the attribute is valid on the current target.
1881 ? diag::err_keyword_not_supported_on_target
1882 : diag::warn_unknown_attribute_ignored)
1883 << AL << AL.getRange();
1884 AL.setInvalid();
1885 return true;
1886 }
1887
1888 return false;
1889}
1890
1891static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1892
1893 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1894 // because 'analyzer_noreturn' does not impact the type.
1896 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1897 if (!VD || (!VD->getType()->isBlockPointerType() &&
1898 !VD->getType()->isFunctionPointerType())) {
1900 ? diag::err_attribute_wrong_decl_type
1901 : diag::warn_attribute_wrong_decl_type)
1902 << AL << AL.isRegularKeywordAttribute()
1904 return;
1905 }
1906 }
1907
1908 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
1909}
1910
1911// PS3 PPU-specific.
1912static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1913 /*
1914 Returning a Vector Class in Registers
1915
1916 According to the PPU ABI specifications, a class with a single member of
1917 vector type is returned in memory when used as the return value of a
1918 function.
1919 This results in inefficient code when implementing vector classes. To return
1920 the value in a single vector register, add the vecreturn attribute to the
1921 class definition. This attribute is also applicable to struct types.
1922
1923 Example:
1924
1925 struct Vector
1926 {
1927 __vector float xyzw;
1928 } __attribute__((vecreturn));
1929
1930 Vector Add(Vector lhs, Vector rhs)
1931 {
1932 Vector result;
1933 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1934 return result; // This will be returned in a register
1935 }
1936 */
1937 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1938 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
1939 return;
1940 }
1941
1942 const auto *R = cast<RecordDecl>(D);
1943 int count = 0;
1944
1945 if (!isa<CXXRecordDecl>(R)) {
1946 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1947 return;
1948 }
1949
1950 if (!cast<CXXRecordDecl>(R)->isPOD()) {
1951 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1952 return;
1953 }
1954
1955 for (const auto *I : R->fields()) {
1956 if ((count == 1) || !I->getType()->isVectorType()) {
1957 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1958 return;
1959 }
1960 count++;
1961 }
1962
1963 D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
1964}
1965
1967 const ParsedAttr &AL) {
1968 if (isa<ParmVarDecl>(D)) {
1969 // [[carries_dependency]] can only be applied to a parameter if it is a
1970 // parameter of a function declaration or lambda.
1972 S.Diag(AL.getLoc(),
1973 diag::err_carries_dependency_param_not_function_decl);
1974 return;
1975 }
1976 }
1977
1978 D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
1979}
1980
1981static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1982 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
1983
1984 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
1985 // about using it as an extension.
1986 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
1987 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
1988
1989 D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
1990}
1991
1992static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1993 uint32_t priority = ConstructorAttr::DefaultPriority;
1994 if (S.getLangOpts().HLSL && AL.getNumArgs()) {
1995 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
1996 return;
1997 }
1998 if (AL.getNumArgs() &&
1999 !S.checkUInt32Argument(AL, AL.getArgAsExpr(0), priority))
2000 return;
2001
2002 D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2003}
2004
2005static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2006 uint32_t priority = DestructorAttr::DefaultPriority;
2007 if (AL.getNumArgs() &&
2008 !S.checkUInt32Argument(AL, AL.getArgAsExpr(0), priority))
2009 return;
2010
2011 D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2012}
2013
2014template <typename AttrTy>
2015static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2016 // Handle the case where the attribute has a text message.
2017 StringRef Str;
2018 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2019 return;
2020
2021 D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2022}
2023
2025 IdentifierInfo *Platform,
2026 VersionTuple Introduced,
2027 VersionTuple Deprecated,
2028 VersionTuple Obsoleted) {
2029 StringRef PlatformName
2030 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2031 if (PlatformName.empty())
2032 PlatformName = Platform->getName();
2033
2034 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2035 // of these steps are needed).
2036 if (!Introduced.empty() && !Deprecated.empty() &&
2037 !(Introduced <= Deprecated)) {
2038 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2039 << 1 << PlatformName << Deprecated.getAsString()
2040 << 0 << Introduced.getAsString();
2041 return true;
2042 }
2043
2044 if (!Introduced.empty() && !Obsoleted.empty() &&
2045 !(Introduced <= Obsoleted)) {
2046 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2047 << 2 << PlatformName << Obsoleted.getAsString()
2048 << 0 << Introduced.getAsString();
2049 return true;
2050 }
2051
2052 if (!Deprecated.empty() && !Obsoleted.empty() &&
2053 !(Deprecated <= Obsoleted)) {
2054 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2055 << 2 << PlatformName << Obsoleted.getAsString()
2056 << 1 << Deprecated.getAsString();
2057 return true;
2058 }
2059
2060 return false;
2061}
2062
2063/// Check whether the two versions match.
2064///
2065/// If either version tuple is empty, then they are assumed to match. If
2066/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2067static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2068 bool BeforeIsOkay) {
2069 if (X.empty() || Y.empty())
2070 return true;
2071
2072 if (X == Y)
2073 return true;
2074
2075 if (BeforeIsOkay && X < Y)
2076 return true;
2077
2078 return false;
2079}
2080
2082 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2083 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2084 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2085 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2086 int Priority, IdentifierInfo *Environment) {
2087 VersionTuple MergedIntroduced = Introduced;
2088 VersionTuple MergedDeprecated = Deprecated;
2089 VersionTuple MergedObsoleted = Obsoleted;
2090 bool FoundAny = false;
2091 bool OverrideOrImpl = false;
2092 switch (AMK) {
2093 case AMK_None:
2094 case AMK_Redeclaration:
2095 OverrideOrImpl = false;
2096 break;
2097
2098 case AMK_Override:
2101 OverrideOrImpl = true;
2102 break;
2103 }
2104
2105 if (D->hasAttrs()) {
2106 AttrVec &Attrs = D->getAttrs();
2107 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2108 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2109 if (!OldAA) {
2110 ++i;
2111 continue;
2112 }
2113
2114 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2115 if (OldPlatform != Platform) {
2116 ++i;
2117 continue;
2118 }
2119
2120 IdentifierInfo *OldEnvironment = OldAA->getEnvironment();
2121 if (OldEnvironment != Environment) {
2122 ++i;
2123 continue;
2124 }
2125
2126 // If there is an existing availability attribute for this platform that
2127 // has a lower priority use the existing one and discard the new
2128 // attribute.
2129 if (OldAA->getPriority() < Priority)
2130 return nullptr;
2131
2132 // If there is an existing attribute for this platform that has a higher
2133 // priority than the new attribute then erase the old one and continue
2134 // processing the attributes.
2135 if (OldAA->getPriority() > Priority) {
2136 Attrs.erase(Attrs.begin() + i);
2137 --e;
2138 continue;
2139 }
2140
2141 FoundAny = true;
2142 VersionTuple OldIntroduced = OldAA->getIntroduced();
2143 VersionTuple OldDeprecated = OldAA->getDeprecated();
2144 VersionTuple OldObsoleted = OldAA->getObsoleted();
2145 bool OldIsUnavailable = OldAA->getUnavailable();
2146
2147 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2148 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2149 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2150 !(OldIsUnavailable == IsUnavailable ||
2151 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2152 if (OverrideOrImpl) {
2153 int Which = -1;
2154 VersionTuple FirstVersion;
2155 VersionTuple SecondVersion;
2156 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2157 Which = 0;
2158 FirstVersion = OldIntroduced;
2159 SecondVersion = Introduced;
2160 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2161 Which = 1;
2162 FirstVersion = Deprecated;
2163 SecondVersion = OldDeprecated;
2164 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2165 Which = 2;
2166 FirstVersion = Obsoleted;
2167 SecondVersion = OldObsoleted;
2168 }
2169
2170 if (Which == -1) {
2171 Diag(OldAA->getLocation(),
2172 diag::warn_mismatched_availability_override_unavail)
2173 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2174 << (AMK == AMK_Override);
2175 } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
2176 // Allow different 'introduced' / 'obsoleted' availability versions
2177 // on a method that implements an optional protocol requirement. It
2178 // makes less sense to allow this for 'deprecated' as the user can't
2179 // see if the method is 'deprecated' as 'respondsToSelector' will
2180 // still return true when the method is deprecated.
2181 ++i;
2182 continue;
2183 } else {
2184 Diag(OldAA->getLocation(),
2185 diag::warn_mismatched_availability_override)
2186 << Which
2187 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2188 << FirstVersion.getAsString() << SecondVersion.getAsString()
2189 << (AMK == AMK_Override);
2190 }
2191 if (AMK == AMK_Override)
2192 Diag(CI.getLoc(), diag::note_overridden_method);
2193 else
2194 Diag(CI.getLoc(), diag::note_protocol_method);
2195 } else {
2196 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2197 Diag(CI.getLoc(), diag::note_previous_attribute);
2198 }
2199
2200 Attrs.erase(Attrs.begin() + i);
2201 --e;
2202 continue;
2203 }
2204
2205 VersionTuple MergedIntroduced2 = MergedIntroduced;
2206 VersionTuple MergedDeprecated2 = MergedDeprecated;
2207 VersionTuple MergedObsoleted2 = MergedObsoleted;
2208
2209 if (MergedIntroduced2.empty())
2210 MergedIntroduced2 = OldIntroduced;
2211 if (MergedDeprecated2.empty())
2212 MergedDeprecated2 = OldDeprecated;
2213 if (MergedObsoleted2.empty())
2214 MergedObsoleted2 = OldObsoleted;
2215
2216 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2217 MergedIntroduced2, MergedDeprecated2,
2218 MergedObsoleted2)) {
2219 Attrs.erase(Attrs.begin() + i);
2220 --e;
2221 continue;
2222 }
2223
2224 MergedIntroduced = MergedIntroduced2;
2225 MergedDeprecated = MergedDeprecated2;
2226 MergedObsoleted = MergedObsoleted2;
2227 ++i;
2228 }
2229 }
2230
2231 if (FoundAny &&
2232 MergedIntroduced == Introduced &&
2233 MergedDeprecated == Deprecated &&
2234 MergedObsoleted == Obsoleted)
2235 return nullptr;
2236
2237 // Only create a new attribute if !OverrideOrImpl, but we want to do
2238 // the checking.
2239 if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2240 MergedDeprecated, MergedObsoleted) &&
2241 !OverrideOrImpl) {
2242 auto *Avail = ::new (Context) AvailabilityAttr(
2243 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2244 Message, IsStrict, Replacement, Priority, Environment);
2245 Avail->setImplicit(Implicit);
2246 return Avail;
2247 }
2248 return nullptr;
2249}
2250
2251static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2252 if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2253 D)) {
2254 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2255 << AL;
2256 return;
2257 }
2258
2259 if (!AL.checkExactlyNumArgs(S, 1))
2260 return;
2261 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2262
2263 IdentifierInfo *II = Platform->Ident;
2264 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2265 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2266 << Platform->Ident;
2267
2268 auto *ND = dyn_cast<NamedDecl>(D);
2269 if (!ND) // We warned about this already, so just return.
2270 return;
2271
2275 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2276 bool IsStrict = AL.getStrictLoc().isValid();
2277 StringRef Str;
2278 if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getMessageExpr()))
2279 Str = SE->getString();
2280 StringRef Replacement;
2281 if (const auto *SE =
2282 dyn_cast_if_present<StringLiteral>(AL.getReplacementExpr()))
2283 Replacement = SE->getString();
2284
2285 if (II->isStr("swift")) {
2286 if (Introduced.isValid() || Obsoleted.isValid() ||
2287 (!IsUnavailable && !Deprecated.isValid())) {
2288 S.Diag(AL.getLoc(),
2289 diag::warn_availability_swift_unavailable_deprecated_only);
2290 return;
2291 }
2292 }
2293
2294 if (II->isStr("fuchsia")) {
2295 std::optional<unsigned> Min, Sub;
2296 if ((Min = Introduced.Version.getMinor()) ||
2297 (Sub = Introduced.Version.getSubminor())) {
2298 S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor);
2299 return;
2300 }
2301 }
2302
2303 if (S.getLangOpts().HLSL && IsStrict)
2304 S.Diag(AL.getStrictLoc(), diag::err_availability_unexpected_parameter)
2305 << "strict" << /* HLSL */ 0;
2306
2307 int PriorityModifier = AL.isPragmaClangAttribute()
2310
2311 const IdentifierLoc *EnvironmentLoc = AL.getEnvironment();
2312 IdentifierInfo *IIEnvironment = nullptr;
2313 if (EnvironmentLoc) {
2314 if (S.getLangOpts().HLSL) {
2315 IIEnvironment = EnvironmentLoc->Ident;
2316 if (AvailabilityAttr::getEnvironmentType(
2317 EnvironmentLoc->Ident->getName()) ==
2318 llvm::Triple::EnvironmentType::UnknownEnvironment)
2319 S.Diag(EnvironmentLoc->Loc, diag::warn_availability_unknown_environment)
2320 << EnvironmentLoc->Ident;
2321 } else {
2322 S.Diag(EnvironmentLoc->Loc, diag::err_availability_unexpected_parameter)
2323 << "environment" << /* C/C++ */ 1;
2324 }
2325 }
2326
2327 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2328 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2329 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2330 Sema::AMK_None, PriorityModifier, IIEnvironment);
2331 if (NewAttr)
2332 D->addAttr(NewAttr);
2333
2334 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2335 // matches before the start of the watchOS platform.
2336 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2337 IdentifierInfo *NewII = nullptr;
2338 if (II->getName() == "ios")
2339 NewII = &S.Context.Idents.get("watchos");
2340 else if (II->getName() == "ios_app_extension")
2341 NewII = &S.Context.Idents.get("watchos_app_extension");
2342
2343 if (NewII) {
2344 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2345 const auto *IOSToWatchOSMapping =
2346 SDKInfo ? SDKInfo->getVersionMapping(
2348 : nullptr;
2349
2350 auto adjustWatchOSVersion =
2351 [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
2352 if (Version.empty())
2353 return Version;
2354 auto MinimumWatchOSVersion = VersionTuple(2, 0);
2355
2356 if (IOSToWatchOSMapping) {
2357 if (auto MappedVersion = IOSToWatchOSMapping->map(
2358 Version, MinimumWatchOSVersion, std::nullopt)) {
2359 return *MappedVersion;
2360 }
2361 }
2362
2363 auto Major = Version.getMajor();
2364 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2365 if (NewMajor >= 2) {
2366 if (Version.getMinor()) {
2367 if (Version.getSubminor())
2368 return VersionTuple(NewMajor, *Version.getMinor(),
2369 *Version.getSubminor());
2370 else
2371 return VersionTuple(NewMajor, *Version.getMinor());
2372 }
2373 return VersionTuple(NewMajor);
2374 }
2375
2376 return MinimumWatchOSVersion;
2377 };
2378
2379 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2380 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2381 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2382
2383 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2384 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2385 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2387 IIEnvironment);
2388 if (NewAttr)
2389 D->addAttr(NewAttr);
2390 }
2391 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2392 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2393 // matches before the start of the tvOS platform.
2394 IdentifierInfo *NewII = nullptr;
2395 if (II->getName() == "ios")
2396 NewII = &S.Context.Idents.get("tvos");
2397 else if (II->getName() == "ios_app_extension")
2398 NewII = &S.Context.Idents.get("tvos_app_extension");
2399
2400 if (NewII) {
2401 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2402 const auto *IOSToTvOSMapping =
2403 SDKInfo ? SDKInfo->getVersionMapping(
2405 : nullptr;
2406
2407 auto AdjustTvOSVersion =
2408 [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
2409 if (Version.empty())
2410 return Version;
2411
2412 if (IOSToTvOSMapping) {
2413 if (auto MappedVersion = IOSToTvOSMapping->map(
2414 Version, VersionTuple(0, 0), std::nullopt)) {
2415 return *MappedVersion;
2416 }
2417 }
2418 return Version;
2419 };
2420
2421 auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
2422 auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
2423 auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
2424
2425 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2426 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2427 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2429 IIEnvironment);
2430 if (NewAttr)
2431 D->addAttr(NewAttr);
2432 }
2433 } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2434 llvm::Triple::IOS &&
2435 S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2436 auto GetSDKInfo = [&]() {
2438 "macOS");
2439 };
2440
2441 // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2442 IdentifierInfo *NewII = nullptr;
2443 if (II->getName() == "ios")
2444 NewII = &S.Context.Idents.get("maccatalyst");
2445 else if (II->getName() == "ios_app_extension")
2446 NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2447 if (NewII) {
2448 auto MinMacCatalystVersion = [](const VersionTuple &V) {
2449 if (V.empty())
2450 return V;
2451 if (V.getMajor() < 13 ||
2452 (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2453 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2454 return V;
2455 };
2456 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2457 ND, AL, NewII, true /*Implicit*/,
2458 MinMacCatalystVersion(Introduced.Version),
2459 MinMacCatalystVersion(Deprecated.Version),
2460 MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2461 IsStrict, Replacement, Sema::AMK_None,
2462 PriorityModifier + Sema::AP_InferredFromOtherPlatform, IIEnvironment);
2463 if (NewAttr)
2464 D->addAttr(NewAttr);
2465 } else if (II->getName() == "macos" && GetSDKInfo() &&
2466 (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2467 !Obsoleted.Version.empty())) {
2468 if (const auto *MacOStoMacCatalystMapping =
2469 GetSDKInfo()->getVersionMapping(
2471 // Infer Mac Catalyst availability from the macOS availability attribute
2472 // if it has versioned availability. Don't infer 'unavailable'. This
2473 // inferred availability has lower priority than the other availability
2474 // attributes that are inferred from 'ios'.
2475 NewII = &S.Context.Idents.get("maccatalyst");
2476 auto RemapMacOSVersion =
2477 [&](const VersionTuple &V) -> std::optional<VersionTuple> {
2478 if (V.empty())
2479 return std::nullopt;
2480 // API_TO_BE_DEPRECATED is 100000.
2481 if (V.getMajor() == 100000)
2482 return VersionTuple(100000);
2483 // The minimum iosmac version is 13.1
2484 return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1),
2485 std::nullopt);
2486 };
2487 std::optional<VersionTuple> NewIntroduced =
2488 RemapMacOSVersion(Introduced.Version),
2489 NewDeprecated =
2490 RemapMacOSVersion(Deprecated.Version),
2491 NewObsoleted =
2492 RemapMacOSVersion(Obsoleted.Version);
2493 if (NewIntroduced || NewDeprecated || NewObsoleted) {
2494 auto VersionOrEmptyVersion =
2495 [](const std::optional<VersionTuple> &V) -> VersionTuple {
2496 return V ? *V : VersionTuple();
2497 };
2498 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2499 ND, AL, NewII, true /*Implicit*/,
2500 VersionOrEmptyVersion(NewIntroduced),
2501 VersionOrEmptyVersion(NewDeprecated),
2502 VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2503 IsStrict, Replacement, Sema::AMK_None,
2504 PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2506 IIEnvironment);
2507 if (NewAttr)
2508 D->addAttr(NewAttr);
2509 }
2510 }
2511 }
2512 }
2513}
2514
2516 const ParsedAttr &AL) {
2517 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 4))
2518 return;
2519
2520 StringRef Language;
2521 if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(0)))
2522 Language = SE->getString();
2523 StringRef DefinedIn;
2524 if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(1)))
2525 DefinedIn = SE->getString();
2526 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2527 StringRef USR;
2528 if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(3)))
2529 USR = SE->getString();
2530
2531 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2532 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration, USR));
2533}
2534
2535template <class T>
2537 typename T::VisibilityType value) {
2538 T *existingAttr = D->getAttr<T>();
2539 if (existingAttr) {
2540 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2541 if (existingValue == value)
2542 return nullptr;
2543 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2544 S.Diag(CI.getLoc(), diag::note_previous_attribute);
2545 D->dropAttr<T>();
2546 }
2547 return ::new (S.Context) T(S.Context, CI, value);
2548}
2549
2551 const AttributeCommonInfo &CI,
2552 VisibilityAttr::VisibilityType Vis) {
2553 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2554}
2555
2556TypeVisibilityAttr *
2558 TypeVisibilityAttr::VisibilityType Vis) {
2559 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2560}
2561
2562static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2563 bool isTypeVisibility) {
2564 // Visibility attributes don't mean anything on a typedef.
2565 if (isa<TypedefNameDecl>(D)) {
2566 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2567 return;
2568 }
2569
2570 // 'type_visibility' can only go on a type or namespace.
2571 if (isTypeVisibility && !(isa<TagDecl>(D) || isa<ObjCInterfaceDecl>(D) ||
2572 isa<NamespaceDecl>(D))) {
2573 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2575 return;
2576 }
2577
2578 // Check that the argument is a string literal.
2579 StringRef TypeStr;
2580 SourceLocation LiteralLoc;
2581 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2582 return;
2583
2584 VisibilityAttr::VisibilityType type;
2585 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2586 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2587 << TypeStr;
2588 return;
2589 }
2590
2591 // Complain about attempts to use protected visibility on targets
2592 // (like Darwin) that don't support it.
2593 if (type == VisibilityAttr::Protected &&
2595 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2596 type = VisibilityAttr::Default;
2597 }
2598
2599 Attr *newAttr;
2600 if (isTypeVisibility) {
2601 newAttr = S.mergeTypeVisibilityAttr(
2602 D, AL, (TypeVisibilityAttr::VisibilityType)type);
2603 } else {
2604 newAttr = S.mergeVisibilityAttr(D, AL, type);
2605 }
2606 if (newAttr)
2607 D->addAttr(newAttr);
2608}
2609
2610static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2611 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2612 if (AL.getNumArgs() > 0) {
2613 Expr *E = AL.getArgAsExpr(0);
2614 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
2615 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
2616 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2617 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2618 return;
2619 }
2620
2621 if (Idx->isSigned() && Idx->isNegative()) {
2622 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2623 << E->getSourceRange();
2624 return;
2625 }
2626
2627 sentinel = Idx->getZExtValue();
2628 }
2629
2630 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2631 if (AL.getNumArgs() > 1) {
2632 Expr *E = AL.getArgAsExpr(1);
2633 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
2634 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
2635 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2636 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2637 return;
2638 }
2639 nullPos = Idx->getZExtValue();
2640
2641 if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
2642 // FIXME: This error message could be improved, it would be nice
2643 // to say what the bounds actually are.
2644 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2645 << E->getSourceRange();
2646 return;
2647 }
2648 }
2649
2650 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2651 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2652 if (isa<FunctionNoProtoType>(FT)) {
2653 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2654 return;
2655 }
2656
2657 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2658 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2659 return;
2660 }
2661 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2662 if (!MD->isVariadic()) {
2663 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2664 return;
2665 }
2666 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2667 if (!BD->isVariadic()) {
2668 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2669 return;
2670 }
2671 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2672 QualType Ty = V->getType();
2673 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2674 const FunctionType *FT = Ty->isFunctionPointerType()
2675 ? D->getFunctionType()
2676 : Ty->castAs<BlockPointerType>()
2677 ->getPointeeType()
2678 ->castAs<FunctionType>();
2679 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2680 int m = Ty->isFunctionPointerType() ? 0 : 1;
2681 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2682 return;
2683 }
2684 } else {
2685 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2686 << AL << AL.isRegularKeywordAttribute()
2688 return;
2689 }
2690 } else {
2691 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2692 << AL << AL.isRegularKeywordAttribute()
2694 return;
2695 }
2696 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2697}
2698
2699static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2700 if (D->getFunctionType() &&
2702 !isa<CXXConstructorDecl>(D)) {
2703 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2704 return;
2705 }
2706 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2707 if (MD->getReturnType()->isVoidType()) {
2708 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2709 return;
2710 }
2711
2712 StringRef Str;
2713 if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
2714 // The standard attribute cannot be applied to variable declarations such
2715 // as a function pointer.
2716 if (isa<VarDecl>(D))
2717 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
2718 << AL << AL.isRegularKeywordAttribute()
2719 << "functions, classes, or enumerations";
2720
2721 // If this is spelled as the standard C++17 attribute, but not in C++17,
2722 // warn about using it as an extension. If there are attribute arguments,
2723 // then claim it's a C++20 extension instead.
2724 // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2725 // extension warning for C23 mode.
2726 const LangOptions &LO = S.getLangOpts();
2727 if (AL.getNumArgs() == 1) {
2728 if (LO.CPlusPlus && !LO.CPlusPlus20)
2729 S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
2730
2731 // Since this is spelled [[nodiscard]], get the optional string
2732 // literal. If in C++ mode, but not in C++20 mode, diagnose as an
2733 // extension.
2734 // FIXME: C23 should support this feature as well, even as an extension.
2735 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2736 return;
2737 } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2738 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2739 }
2740
2741 if ((!AL.isGNUAttribute() &&
2742 !(AL.isStandardAttributeSyntax() && AL.isClangScope())) &&
2743 isa<TypedefNameDecl>(D)) {
2744 S.Diag(AL.getLoc(), diag::warn_unused_result_typedef_unsupported_spelling)
2745 << AL.isGNUScope();
2746 return;
2747 }
2748
2749 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2750}
2751
2752static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2753 // weak_import only applies to variable & function declarations.
2754 bool isDef = false;
2755 if (!D->canBeWeakImported(isDef)) {
2756 if (isDef)
2757 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2758 << "weak_import";
2759 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2760 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2761 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2762 // Nothing to warn about here.
2763 } else
2764 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2766
2767 return;
2768 }
2769
2770 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
2771}
2772
2773// Handles reqd_work_group_size and work_group_size_hint.
2774template <typename WorkGroupAttr>
2775static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2776 uint32_t WGSize[3];
2777 for (unsigned i = 0; i < 3; ++i) {
2778 const Expr *E = AL.getArgAsExpr(i);
2779 if (!S.checkUInt32Argument(AL, E, WGSize[i], i,
2780 /*StrictlyUnsigned=*/true))
2781 return;
2782 if (WGSize[i] == 0) {
2783 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2784 << AL << E->getSourceRange();
2785 return;
2786 }
2787 }
2788
2789 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2790 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2791 Existing->getYDim() == WGSize[1] &&
2792 Existing->getZDim() == WGSize[2]))
2793 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2794
2795 D->addAttr(::new (S.Context)
2796 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
2797}
2798
2799static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2800 if (!AL.hasParsedType()) {
2801 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2802 return;
2803 }
2804
2805 TypeSourceInfo *ParmTSI = nullptr;
2806 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2807 assert(ParmTSI && "no type source info for attribute argument");
2808
2809 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2810 (ParmType->isBooleanType() ||
2811 !ParmType->isIntegralType(S.getASTContext()))) {
2812 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
2813 return;
2814 }
2815
2816 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2817 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2818 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2819 return;
2820 }
2821 }
2822
2823 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
2824}
2825
2827 StringRef Name) {
2828 // Explicit or partial specializations do not inherit
2829 // the section attribute from the primary template.
2830 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2831 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
2833 return nullptr;
2834 }
2835 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2836 if (ExistingAttr->getName() == Name)
2837 return nullptr;
2838 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2839 << 1 /*section*/;
2840 Diag(CI.getLoc(), diag::note_previous_attribute);
2841 return nullptr;
2842 }
2843 return ::new (Context) SectionAttr(Context, CI, Name);
2844}
2845
2846/// Used to implement to perform semantic checking on
2847/// attribute((section("foo"))) specifiers.
2848///
2849/// In this case, "foo" is passed in to be checked. If the section
2850/// specifier is invalid, return an Error that indicates the problem.
2851///
2852/// This is a simple quality of implementation feature to catch errors
2853/// and give good diagnostics in cases when the assembler or code generator
2854/// would otherwise reject the section specifier.
2855llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
2856 if (!Context.getTargetInfo().getTriple().isOSDarwin())
2857 return llvm::Error::success();
2858
2859 // Let MCSectionMachO validate this.
2860 StringRef Segment, Section;
2861 unsigned TAA, StubSize;
2862 bool HasTAA;
2863 return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
2864 TAA, HasTAA, StubSize);
2865}
2866
2867bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2868 if (llvm::Error E = isValidSectionSpecifier(SecName)) {
2869 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2870 << toString(std::move(E)) << 1 /*'section'*/;
2871 return false;
2872 }
2873 return true;
2874}
2875
2876static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2877 // Make sure that there is a string literal as the sections's single
2878 // argument.
2879 StringRef Str;
2880 SourceLocation LiteralLoc;
2881 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2882 return;
2883
2884 if (!S.checkSectionName(LiteralLoc, Str))
2885 return;
2886
2887 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
2888 if (NewAttr) {
2889 D->addAttr(NewAttr);
2891 ObjCPropertyDecl>(D))
2892 S.UnifySection(NewAttr->getName(),
2894 cast<NamedDecl>(D));
2895 }
2896}
2897
2898static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2899 StringRef Str;
2900 SourceLocation LiteralLoc;
2901 // Check that it is a string.
2902 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2903 return;
2904
2905 llvm::CodeModel::Model CM;
2906 if (!CodeModelAttr::ConvertStrToModel(Str, CM)) {
2907 S.Diag(LiteralLoc, diag::err_attr_codemodel_arg) << Str;
2908 return;
2909 }
2910
2911 D->addAttr(::new (S.Context) CodeModelAttr(S.Context, AL, CM));
2912}
2913
2914// This is used for `__declspec(code_seg("segname"))` on a decl.
2915// `#pragma code_seg("segname")` uses checkSectionName() instead.
2916static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
2917 StringRef CodeSegName) {
2918 if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
2919 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2920 << toString(std::move(E)) << 0 /*'code-seg'*/;
2921 return false;
2922 }
2923
2924 return true;
2925}
2926
2928 StringRef Name) {
2929 // Explicit or partial specializations do not inherit
2930 // the code_seg attribute from the primary template.
2931 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2933 return nullptr;
2934 }
2935 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
2936 if (ExistingAttr->getName() == Name)
2937 return nullptr;
2938 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2939 << 0 /*codeseg*/;
2940 Diag(CI.getLoc(), diag::note_previous_attribute);
2941 return nullptr;
2942 }
2943 return ::new (Context) CodeSegAttr(Context, CI, Name);
2944}
2945
2946static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2947 StringRef Str;
2948 SourceLocation LiteralLoc;
2949 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2950 return;
2951 if (!checkCodeSegName(S, LiteralLoc, Str))
2952 return;
2953 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
2954 if (!ExistingAttr->isImplicit()) {
2955 S.Diag(AL.getLoc(),
2956 ExistingAttr->getName() == Str
2957 ? diag::warn_duplicate_codeseg_attribute
2958 : diag::err_conflicting_codeseg_attribute);
2959 return;
2960 }
2961 D->dropAttr<CodeSegAttr>();
2962 }
2963 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
2964 D->addAttr(CSA);
2965}
2966
2967// Check for things we'd like to warn about. Multiversioning issues are
2968// handled later in the process, once we know how many exist.
2969bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2970 enum FirstParam { Unsupported, Duplicate, Unknown };
2971 enum SecondParam { None, CPU, Tune };
2972 enum ThirdParam { Target, TargetClones };
2973 if (AttrStr.contains("fpmath="))
2974 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2975 << Unsupported << None << "fpmath=" << Target;
2976
2977 // Diagnose use of tune if target doesn't support it.
2979 AttrStr.contains("tune="))
2980 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2981 << Unsupported << None << "tune=" << Target;
2982
2983 ParsedTargetAttr ParsedAttrs =
2985
2986 if (!ParsedAttrs.CPU.empty() &&
2987 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.CPU))
2988 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2989 << Unknown << CPU << ParsedAttrs.CPU << Target;
2990
2991 if (!ParsedAttrs.Tune.empty() &&
2992 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
2993 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2994 << Unknown << Tune << ParsedAttrs.Tune << Target;
2995
2996 if (Context.getTargetInfo().getTriple().isRISCV() &&
2997 ParsedAttrs.Duplicate != "")
2998 return Diag(LiteralLoc, diag::err_duplicate_target_attribute)
2999 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3000
3001 if (ParsedAttrs.Duplicate != "")
3002 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3003 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3004
3005 for (const auto &Feature : ParsedAttrs.Features) {
3006 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3007 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3008 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3009 << Unsupported << None << CurFeature << Target;
3010 }
3011
3013 StringRef DiagMsg;
3014 if (ParsedAttrs.BranchProtection.empty())
3015 return false;
3017 ParsedAttrs.BranchProtection, ParsedAttrs.CPU, BPI, DiagMsg)) {
3018 if (DiagMsg.empty())
3019 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3020 << Unsupported << None << "branch-protection" << Target;
3021 return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3022 << DiagMsg;
3023 }
3024 if (!DiagMsg.empty())
3025 Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg;
3026
3027 return false;
3028}
3029
3030// Check Target Version attrs
3032 StringRef &AttrStr, bool &isDefault) {
3033 enum FirstParam { Unsupported };
3034 enum SecondParam { None };
3035 enum ThirdParam { Target, TargetClones, TargetVersion };
3036 if (AttrStr.trim() == "default")
3037 isDefault = true;
3039 AttrStr.split(Features, "+");
3040 for (auto &CurFeature : Features) {
3041 CurFeature = CurFeature.trim();
3042 if (CurFeature == "default")
3043 continue;
3044 if (!Context.getTargetInfo().validateCpuSupports(CurFeature))
3045 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3046 << Unsupported << None << CurFeature << TargetVersion;
3047 }
3048 if (IsArmStreamingFunction(cast<FunctionDecl>(D),
3049 /*IncludeLocallyStreaming=*/false))
3050 return Diag(LiteralLoc, diag::err_sme_streaming_cannot_be_multiversioned);
3051 return false;
3052}
3053
3054static void handleTargetVersionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3055 StringRef Str;
3056 SourceLocation LiteralLoc;
3057 bool isDefault = false;
3058 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3059 S.checkTargetVersionAttr(LiteralLoc, D, Str, isDefault))
3060 return;
3061 // Do not create default only target_version attribute
3062 if (!isDefault) {
3063 TargetVersionAttr *NewAttr =
3064 ::new (S.Context) TargetVersionAttr(S.Context, AL, Str);
3065 D->addAttr(NewAttr);
3066 }
3067}
3068
3069static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3070 StringRef Str;
3071 SourceLocation LiteralLoc;
3072 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3073 S.checkTargetAttr(LiteralLoc, Str))
3074 return;
3075
3076 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3077 D->addAttr(NewAttr);
3078}
3079
3081 SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
3082 Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
3083 SmallVectorImpl<SmallString<64>> &StringsBuffer) {
3084 enum FirstParam { Unsupported, Duplicate, Unknown };
3085 enum SecondParam { None, CPU, Tune };
3086 enum ThirdParam { Target, TargetClones };
3087 HasCommas = HasCommas || Str.contains(',');
3088 const TargetInfo &TInfo = Context.getTargetInfo();
3089 // Warn on empty at the beginning of a string.
3090 if (Str.size() == 0)
3091 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3092 << Unsupported << None << "" << TargetClones;
3093
3094 std::pair<StringRef, StringRef> Parts = {{}, Str};
3095 while (!Parts.second.empty()) {
3096 Parts = Parts.second.split(',');
3097 StringRef Cur = Parts.first.trim();
3098 SourceLocation CurLoc =
3099 Literal->getLocationOfByte(Cur.data() - Literal->getString().data(),
3100 getSourceManager(), getLangOpts(), TInfo);
3101
3102 bool DefaultIsDupe = false;
3103 bool HasCodeGenImpact = false;
3104 if (Cur.empty())
3105 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3106 << Unsupported << None << "" << TargetClones;
3107
3108 if (TInfo.getTriple().isAArch64()) {
3109 // AArch64 target clones specific
3110 if (Cur == "default") {
3111 DefaultIsDupe = HasDefault;
3112 HasDefault = true;
3113 if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3114 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3115 else
3116 StringsBuffer.push_back(Cur);
3117 } else {
3118 std::pair<StringRef, StringRef> CurParts = {{}, Cur};
3120 while (!CurParts.second.empty()) {
3121 CurParts = CurParts.second.split('+');
3122 StringRef CurFeature = CurParts.first.trim();
3123 if (!TInfo.validateCpuSupports(CurFeature)) {
3124 Diag(CurLoc, diag::warn_unsupported_target_attribute)
3125 << Unsupported << None << CurFeature << TargetClones;
3126 continue;
3127 }
3128 if (TInfo.doesFeatureAffectCodeGen(CurFeature))
3129 HasCodeGenImpact = true;
3130 CurFeatures.push_back(CurFeature);
3131 }
3132 // Canonize TargetClones Attributes
3133 llvm::sort(CurFeatures);
3134 SmallString<64> Res;
3135 for (auto &CurFeat : CurFeatures) {
3136 if (!Res.empty())
3137 Res.append("+");
3138 Res.append(CurFeat);
3139 }
3140 if (llvm::is_contained(StringsBuffer, Res) || DefaultIsDupe)
3141 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3142 else if (!HasCodeGenImpact)
3143 // Ignore features in target_clone attribute that don't impact
3144 // code generation
3145 Diag(CurLoc, diag::warn_target_clone_no_impact_options);
3146 else if (!Res.empty()) {
3147 StringsBuffer.push_back(Res);
3148 HasNotDefault = true;
3149 }
3150 }
3151 if (IsArmStreamingFunction(cast<FunctionDecl>(D),
3152 /*IncludeLocallyStreaming=*/false))
3153 return Diag(LiteralLoc,
3154 diag::err_sme_streaming_cannot_be_multiversioned);
3155 } else {
3156 // Other targets ( currently X86 )
3157 if (Cur.starts_with("arch=")) {
3159 Cur.drop_front(sizeof("arch=") - 1)))
3160 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3161 << Unsupported << CPU << Cur.drop_front(sizeof("arch=") - 1)
3162 << TargetClones;
3163 } else if (Cur == "default") {
3164 DefaultIsDupe = HasDefault;
3165 HasDefault = true;
3166 } else if (!Context.getTargetInfo().isValidFeatureName(Cur))
3167 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3168 << Unsupported << None << Cur << TargetClones;
3169 if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3170 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3171 // Note: Add even if there are duplicates, since it changes name mangling.
3172 StringsBuffer.push_back(Cur);
3173 }
3174 }
3175 if (Str.rtrim().ends_with(","))
3176 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3177 << Unsupported << None << "" << TargetClones;
3178 return false;
3179}
3180
3181static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3182 if (S.Context.getTargetInfo().getTriple().isAArch64() &&
3183 !S.Context.getTargetInfo().hasFeature("fmv"))
3184 return;
3185
3186 // Ensure we don't combine these with themselves, since that causes some
3187 // confusing behavior.
3188 if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
3189 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
3190 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
3191 return;
3192 }
3193 if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
3194 return;
3195
3197 SmallVector<SmallString<64>, 2> StringsBuffer;
3198 bool HasCommas = false, HasDefault = false, HasNotDefault = false;
3199
3200 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
3201 StringRef CurStr;
3202 SourceLocation LiteralLoc;
3203 if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) ||
3205 LiteralLoc, CurStr,
3206 cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()), D,
3207 HasDefault, HasCommas, HasNotDefault, StringsBuffer))
3208 return;
3209 }
3210 for (auto &SmallStr : StringsBuffer)
3211 Strings.push_back(SmallStr.str());
3212
3213 if (HasCommas && AL.getNumArgs() > 1)
3214 S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values);
3215
3216 if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasDefault) {
3217 // Add default attribute if there is no one
3218 HasDefault = true;
3219 Strings.push_back("default");
3220 }
3221
3222 if (!HasDefault) {
3223 S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default);
3224 return;
3225 }
3226
3227 // FIXME: We could probably figure out how to get this to work for lambdas
3228 // someday.
3229 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
3230 if (MD->getParent()->isLambda()) {
3231 S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support)
3232 << static_cast<unsigned>(MultiVersionKind::TargetClones)
3233 << /*Lambda*/ 9;
3234 return;
3235 }
3236 }
3237
3238 // No multiversion if we have default version only.
3239 if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasNotDefault)
3240 return;
3241
3242 cast<FunctionDecl>(D)->setIsMultiVersion();
3243 TargetClonesAttr *NewAttr = ::new (S.Context)
3244 TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size());
3245 D->addAttr(NewAttr);
3246}
3247
3248static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3249 Expr *E = AL.getArgAsExpr(0);
3250 uint32_t VecWidth;
3251 if (!S.checkUInt32Argument(AL, E, VecWidth)) {
3252 AL.setInvalid();
3253 return;
3254 }
3255
3256 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3257 if (Existing && Existing->getVectorWidth() != VecWidth) {
3258 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3259 return;
3260 }
3261
3262 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3263}
3264
3265static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3266 Expr *E = AL.getArgAsExpr(0);
3268 FunctionDecl *FD = nullptr;
3270
3271 // gcc only allows for simple identifiers. Since we support more than gcc, we
3272 // will warn the user.
3273 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3274 if (DRE->hasQualifier())
3275 S.Diag(Loc, diag::warn_cleanup_ext);
3276 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3277 NI = DRE->getNameInfo();
3278 if (!FD) {
3279 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3280 << NI.getName();
3281 return;
3282 }
3283 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3284 if (ULE->hasExplicitTemplateArgs())
3285 S.Diag(Loc, diag::warn_cleanup_ext);
3287 NI = ULE->getNameInfo();
3288 if (!FD) {
3289 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3290 << NI.getName();
3291 if (ULE->getType() == S.Context.OverloadTy)
3293 return;
3294 }
3295 } else {
3296 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3297 return;
3298 }
3299
3300 if (FD->getNumParams() != 1) {
3301 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3302 << NI.getName();
3303 return;
3304 }
3305
3306 // We're currently more strict than GCC about what function types we accept.
3307 // If this ever proves to be a problem it should be easy to fix.
3308 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3309 QualType ParamTy = FD->getParamDecl(0)->getType();
3311 ParamTy, Ty) != Sema::Compatible) {
3312 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3313 << NI.getName() << ParamTy << Ty;
3314 return;
3315 }
3316 VarDecl *VD = cast<VarDecl>(D);
3317 // Create a reference to the variable declaration. This is a fake/dummy
3318 // reference.
3319 DeclRefExpr *VariableReference = DeclRefExpr::Create(
3320 S.Context, NestedNameSpecifierLoc{}, FD->getLocation(), VD, false,
3321 DeclarationNameInfo{VD->getDeclName(), VD->getLocation()}, VD->getType(),
3322 VK_LValue);
3323
3324 // Create a unary operator expression that represents taking the address of
3325 // the variable. This is a fake/dummy expression.
3326 Expr *AddressOfVariable = UnaryOperator::Create(
3327 S.Context, VariableReference, UnaryOperatorKind::UO_AddrOf,
3329 +false, FPOptionsOverride{});
3330
3331 // Create a function call expression. This is a fake/dummy call expression.
3332 CallExpr *FunctionCallExpression =
3333 CallExpr::Create(S.Context, E, ArrayRef{AddressOfVariable},
3335
3336 if (S.CheckFunctionCall(FD, FunctionCallExpression,
3337 FD->getType()->getAs<FunctionProtoType>())) {
3338 return;
3339 }
3340
3341 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3342}
3343
3345 const ParsedAttr &AL) {
3346 if (!AL.isArgIdent(0)) {
3347 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3348 << AL << 0 << AANT_ArgumentIdentifier;
3349 return;
3350 }
3351
3352 EnumExtensibilityAttr::Kind ExtensibilityKind;
3353 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3354 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3355 ExtensibilityKind)) {
3356 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3357 return;
3358 }
3359
3360 D->addAttr(::new (S.Context)
3361 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3362}
3363
3364/// Handle __attribute__((format_arg((idx)))) attribute based on
3365/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3366static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3367 const Expr *IdxExpr = AL.getArgAsExpr(0);
3368 ParamIdx Idx;
3369 if (!S.checkFunctionOrMethodParameterIndex(D, AL, 1, IdxExpr, Idx))
3370 return;
3371
3372 // Make sure the format string is really a string.
3374
3375 bool NotNSStringTy = !S.ObjC().isNSStringType(Ty);
3376 if (NotNSStringTy && !S.ObjC().isCFStringType(Ty) &&
3377 (!Ty->isPointerType() ||
3379 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3380 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3381 return;
3382 }
3384 // replace instancetype with the class type
3385 auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl();
3386 if (Ty->getAs<TypedefType>() == Instancetype)
3387 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3388 if (auto *Interface = OMD->getClassInterface())
3390 QualType(Interface->getTypeForDecl(), 0));
3391 if (!S.ObjC().isNSStringType(Ty, /*AllowNSAttributedString=*/true) &&
3392 !S.ObjC().isCFStringType(Ty) &&
3393 (!Ty->isPointerType() ||
3395 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3396 << (NotNSStringTy ? "string type" : "NSString")
3397 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3398 return;
3399 }
3400
3401 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3402}
3403
3412
3413/// getFormatAttrKind - Map from format attribute names to supported format
3414/// types.
3415static FormatAttrKind getFormatAttrKind(StringRef Format) {
3416 return llvm::StringSwitch<FormatAttrKind>(Format)
3417 // Check for formats that get handled specially.
3418 .Case("NSString", NSStringFormat)
3419 .Case("CFString", CFStringFormat)
3420 .Case("strftime", StrftimeFormat)
3421
3422 // Otherwise, check for supported formats.
3423 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3424 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3425 .Case("kprintf", SupportedFormat) // OpenBSD.
3426 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3427 .Case("os_trace", SupportedFormat)
3428 .Case("os_log", SupportedFormat)
3429
3430 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3431 .Default(InvalidFormat);
3432}
3433
3434/// Handle __attribute__((init_priority(priority))) attributes based on
3435/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3436static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3437 if (!S.getLangOpts().CPlusPlus) {
3438 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3439 return;
3440 }
3441
3442 if (S.getLangOpts().HLSL) {
3443 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
3444 return;
3445 }
3446
3448 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3449 AL.setInvalid();
3450 return;
3451 }
3452 QualType T = cast<VarDecl>(D)->getType();
3453 if (S.Context.getAsArrayType(T))
3455 if (!T->getAs<RecordType>()) {
3456 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3457 AL.setInvalid();
3458 return;
3459 }
3460
3461 Expr *E = AL.getArgAsExpr(0);
3462 uint32_t prioritynum;
3463 if (!S.checkUInt32Argument(AL, E, prioritynum)) {
3464 AL.setInvalid();
3465 return;
3466 }
3467
3468 // Only perform the priority check if the attribute is outside of a system
3469 // header. Values <= 100 are reserved for the implementation, and libc++
3470 // benefits from being able to specify values in that range.
3471 if ((prioritynum < 101 || prioritynum > 65535) &&
3473 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3474 << E->getSourceRange() << AL << 101 << 65535;
3475 AL.setInvalid();
3476 return;
3477 }
3478 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3479}
3480
3482 StringRef NewUserDiagnostic) {
3483 if (const auto *EA = D->getAttr<ErrorAttr>()) {
3484 std::string NewAttr = CI.getNormalizedFullName();
3485 assert((NewAttr == "error" || NewAttr == "warning") &&
3486 "unexpected normalized full name");
3487 bool Match = (EA->isError() && NewAttr == "error") ||
3488 (EA->isWarning() && NewAttr == "warning");
3489 if (!Match) {
3490 Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
3491 << CI << EA
3492 << (CI.isRegularKeywordAttribute() ||
3493 EA->isRegularKeywordAttribute());
3494 Diag(CI.getLoc(), diag::note_conflicting_attribute);
3495 return nullptr;
3496 }
3497 if (EA->getUserDiagnostic() != NewUserDiagnostic) {
3498 Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
3499 Diag(EA->getLoc(), diag::note_previous_attribute);
3500 }
3501 D->dropAttr<ErrorAttr>();
3502 }
3503 return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
3504}
3505
3507 IdentifierInfo *Format, int FormatIdx,
3508 int FirstArg) {
3509 // Check whether we already have an equivalent format attribute.
3510 for (auto *F : D->specific_attrs<FormatAttr>()) {
3511 if (F->getType() == Format &&
3512 F->getFormatIdx() == FormatIdx &&
3513 F->getFirstArg() == FirstArg) {
3514 // If we don't have a valid location for this attribute, adopt the
3515 // location.
3516 if (F->getLocation().isInvalid())
3517 F->setRange(CI.getRange());
3518 return nullptr;
3519 }
3520 }
3521
3522 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3523}
3524
3525/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3526/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3527static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3528 if (!AL.isArgIdent(0)) {
3529 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3530 << AL << 1 << AANT_ArgumentIdentifier;
3531 return;
3532 }
3533
3534 // In C++ the implicit 'this' function parameter also counts, and they are
3535 // counted from one.
3536 bool HasImplicitThisParam = isInstanceMethod(D);
3537 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3538
3539 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3540 StringRef Format = II->getName();
3541
3542 if (normalizeName(Format)) {
3543 // If we've modified the string name, we need a new identifier for it.
3544 II = &S.Context.Idents.get(Format);
3545 }
3546
3547 // Check for supported formats.
3548 FormatAttrKind Kind = getFormatAttrKind(Format);
3549
3550 if (Kind == IgnoredFormat)
3551 return;
3552
3553 if (Kind == InvalidFormat) {
3554 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3555 << AL << II->getName();
3556 return;
3557 }
3558
3559 // checks for the 2nd argument
3560 Expr *IdxExpr = AL.getArgAsExpr(1);
3561 uint32_t Idx;
3562 if (!S.checkUInt32Argument(AL, IdxExpr, Idx, 2))
3563 return;
3564
3565 if (Idx < 1 || Idx > NumArgs) {
3566 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3567 << AL << 2 << IdxExpr->getSourceRange();
3568 return;
3569 }
3570
3571 // FIXME: Do we need to bounds check?
3572 unsigned ArgIdx = Idx - 1;
3573
3574 if (HasImplicitThisParam) {
3575 if (ArgIdx == 0) {
3576 S.Diag(AL.getLoc(),
3577 diag::err_format_attribute_implicit_this_format_string)
3578 << IdxExpr->getSourceRange();
3579 return;
3580 }
3581 ArgIdx--;
3582 }
3583
3584 // make sure the format string is really a string
3585 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3586
3587 if (!S.ObjC().isNSStringType(Ty, true) && !S.ObjC().isCFStringType(Ty) &&
3588 (!Ty->isPointerType() ||
3590 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3591 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx);
3592 return;
3593 }
3594
3595 // check the 3rd argument
3596 Expr *FirstArgExpr = AL.getArgAsExpr(2);
3597 uint32_t FirstArg;
3598 if (!S.checkUInt32Argument(AL, FirstArgExpr, FirstArg, 3))
3599 return;
3600
3601 // FirstArg == 0 is is always valid.
3602 if (FirstArg != 0) {
3603 if (Kind == StrftimeFormat) {
3604 // If the kind is strftime, FirstArg must be 0 because strftime does not
3605 // use any variadic arguments.
3606 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3607 << FirstArgExpr->getSourceRange()
3608 << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(), "0");
3609 return;
3610 } else if (isFunctionOrMethodVariadic(D)) {
3611 // Else, if the function is variadic, then FirstArg must be 0 or the
3612 // "position" of the ... parameter. It's unusual to use 0 with variadic
3613 // functions, so the fixit proposes the latter.
3614 if (FirstArg != NumArgs + 1) {
3615 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3616 << AL << 3 << FirstArgExpr->getSourceRange()
3618 std::to_string(NumArgs + 1));
3619 return;
3620 }
3621 } else {
3622 // Inescapable GCC compatibility diagnostic.
3623 S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
3624 if (FirstArg <= Idx) {
3625 // Else, the function is not variadic, and FirstArg must be 0 or any
3626 // parameter after the format parameter. We don't offer a fixit because
3627 // there are too many possible good values.
3628 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3629 << AL << 3 << FirstArgExpr->getSourceRange();
3630 return;
3631 }
3632 }
3633 }
3634
3635 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3636 if (NewAttr)
3637 D->addAttr(NewAttr);
3638}
3639
3640/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3641static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3642 // The index that identifies the callback callee is mandatory.
3643 if (AL.getNumArgs() == 0) {
3644 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3645 << AL.getRange();
3646 return;
3647 }
3648
3649 bool HasImplicitThisParam = isInstanceMethod(D);
3650 int32_t NumArgs = getFunctionOrMethodNumParams(D);
3651
3652 FunctionDecl *FD = D->getAsFunction();
3653 assert(FD && "Expected a function declaration!");
3654
3655 llvm::StringMap<int> NameIdxMapping;
3656 NameIdxMapping["__"] = -1;
3657
3658 NameIdxMapping["this"] = 0;
3659
3660 int Idx = 1;
3661 for (const ParmVarDecl *PVD : FD->parameters())
3662 NameIdxMapping[PVD->getName()] = Idx++;
3663
3664 auto UnknownName = NameIdxMapping.end();
3665
3666 SmallVector<int, 8> EncodingIndices;
3667 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3668 SourceRange SR;
3669 int32_t ArgIdx;
3670
3671 if (AL.isArgIdent(I)) {
3672 IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3673 auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3674 if (It == UnknownName) {
3675 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3676 << IdLoc->Ident << IdLoc->Loc;
3677 return;
3678 }
3679
3680 SR = SourceRange(IdLoc->Loc);
3681 ArgIdx = It->second;
3682 } else if (AL.isArgExpr(I)) {
3683 Expr *IdxExpr = AL.getArgAsExpr(I);
3684
3685 // If the expression is not parseable as an int32_t we have a problem.
3686 if (!S.checkUInt32Argument(AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3687 false)) {
3688 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3689 << AL << (I + 1) << IdxExpr->getSourceRange();
3690 return;
3691 }
3692
3693 // Check oob, excluding the special values, 0 and -1.
3694 if (ArgIdx < -1 || ArgIdx > NumArgs) {
3695 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3696 << AL << (I + 1) << IdxExpr->getSourceRange();
3697 return;
3698 }
3699
3700 SR = IdxExpr->getSourceRange();
3701 } else {
3702 llvm_unreachable("Unexpected ParsedAttr argument type!");
3703 }
3704
3705 if (ArgIdx == 0 && !HasImplicitThisParam) {
3706 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3707 << (I + 1) << SR;
3708 return;
3709 }
3710
3711 // Adjust for the case we do not have an implicit "this" parameter. In this
3712 // case we decrease all positive values by 1 to get LLVM argument indices.
3713 if (!HasImplicitThisParam && ArgIdx > 0)
3714 ArgIdx -= 1;
3715
3716 EncodingIndices.push_back(ArgIdx);
3717 }
3718
3719 int CalleeIdx = EncodingIndices.front();
3720 // Check if the callee index is proper, thus not "this" and not "unknown".
3721 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3722 // is false and positive if "HasImplicitThisParam" is true.
3723 if (CalleeIdx < (int)HasImplicitThisParam) {
3724 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3725 << AL.getRange();
3726 return;
3727 }
3728
3729 // Get the callee type, note the index adjustment as the AST doesn't contain
3730 // the this type (which the callee cannot reference anyway!).
3731 const Type *CalleeType =
3732 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3733 .getTypePtr();
3734 if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3735 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3736 << AL.getRange();
3737 return;
3738 }
3739
3740 const Type *CalleeFnType =
3742
3743 // TODO: Check the type of the callee arguments.
3744
3745 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3746 if (!CalleeFnProtoType) {
3747 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3748 << AL.getRange();
3749 return;
3750 }
3751
3752 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3753 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3754 << AL << (unsigned)(EncodingIndices.size() - 1);
3755 return;
3756 }
3757
3758 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3759 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3760 << AL << (unsigned)(EncodingIndices.size() - 1);
3761 return;
3762 }
3763
3764 if (CalleeFnProtoType->isVariadic()) {
3765 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3766 return;
3767 }
3768
3769 // Do not allow multiple callback attributes.
3770 if (D->hasAttr<CallbackAttr>()) {
3771 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3772 return;
3773 }
3774
3775 D->addAttr(::new (S.Context) CallbackAttr(
3776 S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3777}
3778
3779static bool isFunctionLike(const Type &T) {
3780 // Check for explicit function types.
3781 // 'called_once' is only supported in Objective-C and it has
3782 // function pointers and block pointers.
3784}
3785
3786/// Handle 'called_once' attribute.
3787static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3788 // 'called_once' only applies to parameters representing functions.
3789 QualType T = cast<ParmVarDecl>(D)->getType();
3790
3791 if (!isFunctionLike(*T)) {
3792 S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
3793 return;
3794 }
3795
3796 D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
3797}
3798
3799static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3800 // Try to find the underlying union declaration.
3801 RecordDecl *RD = nullptr;
3802 const auto *TD = dyn_cast<TypedefNameDecl>(D);
3803 if (TD && TD->getUnderlyingType()->isUnionType())
3804 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3805 else
3806 RD = dyn_cast<RecordDecl>(D);
3807
3808 if (!RD || !RD->isUnion()) {
3809 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3811 return;
3812 }
3813
3814 if (!RD->isCompleteDefinition()) {
3815 if (!RD->isBeingDefined())
3816 S.Diag(AL.getLoc(),
3817 diag::warn_transparent_union_attribute_not_definition);
3818 return;
3819 }
3820
3822 FieldEnd = RD->field_end();
3823 if (Field == FieldEnd) {
3824 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3825 return;
3826 }
3827
3828 FieldDecl *FirstField = *Field;
3829 QualType FirstType = FirstField->getType();
3830 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3831 S.Diag(FirstField->getLocation(),
3832 diag::warn_transparent_union_attribute_floating)
3833 << FirstType->isVectorType() << FirstType;
3834 return;
3835 }
3836
3837 if (FirstType->isIncompleteType())
3838 return;
3839 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3840 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3841 for (; Field != FieldEnd; ++Field) {
3842 QualType FieldType = Field->getType();
3843 if (FieldType->isIncompleteType())
3844 return;
3845 // FIXME: this isn't fully correct; we also need to test whether the
3846 // members of the union would all have the same calling convention as the
3847 // first member of the union. Checking just the size and alignment isn't
3848 // sufficient (consider structs passed on the stack instead of in registers
3849 // as an example).
3850 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3851 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3852 // Warn if we drop the attribute.
3853 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3854 unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
3855 : S.Context.getTypeAlign(FieldType);
3856 S.Diag(Field->getLocation(),
3857 diag::warn_transparent_union_attribute_field_size_align)
3858 << isSize << *Field << FieldBits;
3859 unsigned FirstBits = isSize ? FirstSize : FirstAlign;
3860 S.Diag(FirstField->getLocation(),
3861 diag::note_transparent_union_first_field_size_align)
3862 << isSize << FirstBits;
3863 return;
3864 }
3865 }
3866
3867 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3868}
3869
3871 StringRef Str, MutableArrayRef<Expr *> Args) {
3872 auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
3874 CI, MutableArrayRef<Expr *>(Attr->args_begin(), Attr->args_end()))) {
3875 D->addAttr(Attr);
3876 }
3877}
3878
3879static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3880 // Make sure that there is a string literal as the annotation's first
3881 // argument.
3882 StringRef Str;
3883 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3884 return;
3885
3887 Args.reserve(AL.getNumArgs() - 1);
3888 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
3889 assert(!AL.isArgIdent(Idx));
3890 Args.push_back(AL.getArgAsExpr(Idx));
3891 }
3892
3893 S.AddAnnotationAttr(D, AL, Str, Args);
3894}
3895
3896static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3897 S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3898}
3899
3901 AlignValueAttr TmpAttr(Context, CI, E);
3902 SourceLocation AttrLoc = CI.getLoc();
3903
3904 QualType T;
3905 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3906 T = TD->getUnderlyingType();
3907 else if (const auto *VD = dyn_cast<ValueDecl>(D))
3908 T = VD->getType();
3909 else
3910 llvm_unreachable("Unknown decl type for align_value");
3911
3912 if (!T->isDependentType() && !T->isAnyPointerType() &&
3914 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3915 << &TmpAttr << T << D->getSourceRange();
3916 return;
3917 }
3918
3919 if (!E->isValueDependent()) {
3920 llvm::APSInt Alignment;
3922 E, &Alignment, diag::err_align_value_attribute_argument_not_int);
3923 if (ICE.isInvalid())
3924 return;
3925
3926 if (!Alignment.isPowerOf2()) {
3927 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3928 << E->getSourceRange();
3929 return;
3930 }
3931
3932 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3933 return;
3934 }
3935
3936 // Save dependent expressions in the AST to be instantiated.
3937 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3938}
3939
3940static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3941 if (AL.hasParsedType()) {
3942 const ParsedType &TypeArg = AL.getTypeArg();
3943 TypeSourceInfo *TInfo;
3944 (void)S.GetTypeFromParser(
3945 ParsedType::getFromOpaquePtr(TypeArg.getAsOpaquePtr()), &TInfo);
3946 if (AL.isPackExpansion() &&
3948 S.Diag(AL.getEllipsisLoc(),
3949 diag::err_pack_expansion_without_parameter_packs);
3950 return;
3951 }
3952
3953 if (!AL.isPackExpansion() &&
3955 TInfo, Sema::UPPC_Expression))
3956 return;
3957
3958 S.AddAlignedAttr(D, AL, TInfo, AL.isPackExpansion());
3959 return;
3960 }
3961
3962 // check the attribute arguments.
3963 if (AL.getNumArgs() > 1) {
3964 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3965 return;
3966 }
3967
3968 if (AL.getNumArgs() == 0) {
3969 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3970 return;
3971 }
3972
3973 Expr *E = AL.getArgAsExpr(0);
3975 S.Diag(AL.getEllipsisLoc(),
3976 diag::err_pack_expansion_without_parameter_packs);
3977 return;
3978 }
3979
3981 return;
3982
3983 S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3984}
3985
3986/// Perform checking of type validity
3987///
3988/// C++11 [dcl.align]p1:
3989/// An alignment-specifier may be applied to a variable or to a class
3990/// data member, but it shall not be applied to a bit-field, a function
3991/// parameter, the formal parameter of a catch clause, or a variable
3992/// declared with the register storage class specifier. An
3993/// alignment-specifier may also be applied to the declaration of a class
3994/// or enumeration type.
3995/// CWG 2354:
3996/// CWG agreed to remove permission for alignas to be applied to
3997/// enumerations.
3998/// C11 6.7.5/2:
3999/// An alignment attribute shall not be specified in a declaration of
4000/// a typedef, or a bit-field, or a function, or a parameter, or an
4001/// object declared with the register storage-class specifier.
4003 const AlignedAttr &Attr,
4004 SourceLocation AttrLoc) {
4005 int DiagKind = -1;
4006 if (isa<ParmVarDecl>(D)) {
4007 DiagKind = 0;
4008 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
4009 if (VD->getStorageClass() == SC_Register)
4010 DiagKind = 1;
4011 if (VD->isExceptionVariable())
4012 DiagKind = 2;
4013 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
4014 if (FD->isBitField())
4015 DiagKind = 3;
4016 } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4017 if (ED->getLangOpts().CPlusPlus)
4018 DiagKind = 4;
4019 } else if (!isa<TagDecl>(D)) {
4020 return S.Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
4022 << (Attr.isC11() ? ExpectedVariableOrField
4024 }
4025 if (DiagKind != -1) {
4026 return S.Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4027 << &Attr << DiagKind;
4028 }
4029 return false;
4030}
4031
4033 bool IsPackExpansion) {
4034 AlignedAttr TmpAttr(Context, CI, true, E);
4035 SourceLocation AttrLoc = CI.getLoc();
4036
4037 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4038 if (TmpAttr.isAlignas() &&
4039 validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4040 return;
4041
4042 if (E->isValueDependent()) {
4043 // We can't support a dependent alignment on a non-dependent type,
4044 // because we have no way to model that a type is "alignment-dependent"
4045 // but not dependent in any other way.
4046 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4047 if (!TND->getUnderlyingType()->isDependentType()) {
4048 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4049 << E->getSourceRange();
4050 return;
4051 }
4052 }
4053
4054 // Save dependent expressions in the AST to be instantiated.
4055 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4056 AA->setPackExpansion(IsPackExpansion);
4057 D->addAttr(AA);
4058 return;
4059 }
4060
4061 // FIXME: Cache the number on the AL object?
4062 llvm::APSInt Alignment;
4064 E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4065 if (ICE.isInvalid())
4066 return;
4067
4069 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4070 MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192));
4071 if (Alignment > MaximumAlignment) {
4072 Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4074 return;
4075 }
4076
4077 uint64_t AlignVal = Alignment.getZExtValue();
4078 // C++11 [dcl.align]p2:
4079 // -- if the constant expression evaluates to zero, the alignment
4080 // specifier shall have no effect
4081 // C11 6.7.5p6:
4082 // An alignment specification of zero has no effect.
4083 if (!(TmpAttr.isAlignas() && !Alignment)) {
4084 if (!llvm::isPowerOf2_64(AlignVal)) {
4085 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4086 << E->getSourceRange();
4087 return;
4088 }
4089 }
4090
4091 const auto *VD = dyn_cast<VarDecl>(D);
4092 if (VD) {
4093 unsigned MaxTLSAlign =
4095 .getQuantity();
4096 if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4097 VD->getTLSKind() != VarDecl::TLS_None) {
4098 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4099 << (unsigned)AlignVal << VD << MaxTLSAlign;
4100 return;
4101 }
4102 }
4103
4104 // On AIX, an aligned attribute can not decrease the alignment when applied
4105 // to a variable declaration with vector type.
4106 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4107 const Type *Ty = VD->getType().getTypePtr();
4108 if (Ty->isVectorType() && AlignVal < 16) {
4109 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4110 << VD->getType() << 16;
4111 return;
4112 }
4113 }
4114
4115 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4116 AA->setPackExpansion(IsPackExpansion);
4117 AA->setCachedAlignmentValue(
4118 static_cast<unsigned>(AlignVal * Context.getCharWidth()));
4119 D->addAttr(AA);
4120}
4121
4123 TypeSourceInfo *TS, bool IsPackExpansion) {
4124 AlignedAttr TmpAttr(Context, CI, false, TS);
4125 SourceLocation AttrLoc = CI.getLoc();
4126
4127 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4128 if (TmpAttr.isAlignas() &&
4129 validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4130 return;
4131
4132 if (TS->getType()->isDependentType()) {
4133 // We can't support a dependent alignment on a non-dependent type,
4134 // because we have no way to model that a type is "type-dependent"
4135 // but not dependent in any other way.
4136 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4137 if (!TND->getUnderlyingType()->isDependentType()) {
4138 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4139 << TS->getTypeLoc().getSourceRange();
4140 return;
4141 }
4142 }
4143
4144 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4145 AA->setPackExpansion(IsPackExpansion);
4146 D->addAttr(AA);
4147 return;
4148 }
4149
4150 const auto *VD = dyn_cast<VarDecl>(D);
4151 unsigned AlignVal = TmpAttr.getAlignment(Context);
4152 // On AIX, an aligned attribute can not decrease the alignment when applied
4153 // to a variable declaration with vector type.
4154 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4155 const Type *Ty = VD->getType().getTypePtr();
4156 if (Ty->isVectorType() &&
4157 Context.toCharUnitsFromBits(AlignVal).getQuantity() < 16) {
4158 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4159 << VD->getType() << 16;
4160 return;
4161 }
4162 }
4163
4164 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4165 AA->setPackExpansion(IsPackExpansion);
4166 AA->setCachedAlignmentValue(AlignVal);
4167 D->addAttr(AA);
4168}
4169
4171 assert(D->hasAttrs() && "no attributes on decl");
4172
4173 QualType UnderlyingTy, DiagTy;
4174 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4175 UnderlyingTy = DiagTy = VD->getType();
4176 } else {
4177 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4178 if (const auto *ED = dyn_cast<EnumDecl>(D))
4179 UnderlyingTy = ED->getIntegerType();
4180 }
4181 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4182 return;
4183
4184 // C++11 [dcl.align]p5, C11 6.7.5/4:
4185 // The combined effect of all alignment attributes in a declaration shall
4186 // not specify an alignment that is less strict than the alignment that
4187 // would otherwise be required for the entity being declared.
4188 AlignedAttr *AlignasAttr = nullptr;
4189 AlignedAttr *LastAlignedAttr = nullptr;
4190 unsigned Align = 0;
4191 for (auto *I : D->specific_attrs<AlignedAttr>()) {
4192 if (I->isAlignmentDependent())
4193 return;
4194 if (I->isAlignas())
4195 AlignasAttr = I;
4196 Align = std::max(Align, I->getAlignment(Context));
4197 LastAlignedAttr = I;
4198 }
4199
4200 if (Align && DiagTy->isSizelessType()) {
4201 Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4202 << LastAlignedAttr << DiagTy;
4203 } else if (AlignasAttr && Align) {
4204 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4205 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4206 if (NaturalAlign > RequestedAlign)
4207 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4208 << DiagTy << (unsigned)NaturalAlign.getQuantity();
4209 }
4210}
4211
4213 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4214 MSInheritanceModel ExplicitModel) {
4215 assert(RD->hasDefinition() && "RD has no definition!");
4216
4217 // We may not have seen base specifiers or any virtual methods yet. We will
4218 // have to wait until the record is defined to catch any mismatches.
4219 if (!RD->getDefinition()->isCompleteDefinition())
4220 return false;
4221
4222 // The unspecified model never matches what a definition could need.
4223 if (ExplicitModel == MSInheritanceModel::Unspecified)
4224 return false;
4225
4226 if (BestCase) {
4227 if (RD->calculateInheritanceModel() == ExplicitModel)
4228 return false;
4229 } else {
4230 if (RD->calculateInheritanceModel() <= ExplicitModel)
4231 return false;
4232 }
4233
4234 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4235 << 0 /*definition*/;
4236 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4237 return true;
4238}
4239
4240/// parseModeAttrArg - Parses attribute mode string and returns parsed type
4241/// attribute.
4242static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4243 bool &IntegerMode, bool &ComplexMode,
4244 FloatModeKind &ExplicitType) {
4245 IntegerMode = true;
4246 ComplexMode = false;
4247 ExplicitType = FloatModeKind::NoFloat;
4248 switch (Str.size()) {
4249 case 2:
4250 switch (Str[0]) {
4251 case 'Q':
4252 DestWidth = 8;
4253 break;
4254 case 'H':
4255 DestWidth = 16;
4256 break;
4257 case 'S':
4258 DestWidth = 32;
4259 break;
4260 case 'D':
4261 DestWidth = 64;
4262 break;
4263 case 'X':
4264 DestWidth = 96;
4265 break;
4266 case 'K': // KFmode - IEEE quad precision (__float128)
4267 ExplicitType = FloatModeKind::Float128;
4268 DestWidth = Str[1] == 'I' ? 0 : 128;
4269 break;
4270 case 'T':
4271 ExplicitType = FloatModeKind::LongDouble;
4272 DestWidth = 128;
4273 break;
4274 case 'I':
4275 ExplicitType = FloatModeKind::Ibm128;
4276 DestWidth = Str[1] == 'I' ? 0 : 128;
4277 break;
4278 }
4279 if (Str[1] == 'F') {
4280 IntegerMode = false;
4281 } else if (Str[1] == 'C') {
4282 IntegerMode = false;
4283 ComplexMode = true;
4284 } else if (Str[1] != 'I') {
4285 DestWidth = 0;
4286 }
4287 break;
4288 case 4:
4289 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4290 // pointer on PIC16 and other embedded platforms.
4291 if (Str == "word")
4292 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4293 else if (Str == "byte")
4294 DestWidth = S.Context.getTargetInfo().getCharWidth();
4295 break;
4296 case 7:
4297 if (Str == "pointer")
4299 break;
4300 case 11:
4301 if (Str == "unwind_word")
4302 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4303 break;
4304 }
4305}
4306
4307/// handleModeAttr - This attribute modifies the width of a decl with primitive
4308/// type.
4309///
4310/// Despite what would be logical, the mode attribute is a decl attribute, not a
4311/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4312/// HImode, not an intermediate pointer.
4313static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4314 // This attribute isn't documented, but glibc uses it. It changes
4315 // the width of an int or unsigned int to the specified size.
4316 if (!AL.isArgIdent(0)) {
4317 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4318 << AL << AANT_ArgumentIdentifier;
4319 return;
4320 }
4321
4322 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4323
4324 S.AddModeAttr(D, AL, Name);
4325}
4326
4328 IdentifierInfo *Name, bool InInstantiation) {
4329 StringRef Str = Name->getName();
4330 normalizeName(Str);
4331 SourceLocation AttrLoc = CI.getLoc();
4332
4333 unsigned DestWidth = 0;
4334 bool IntegerMode = true;
4335 bool ComplexMode = false;
4337 llvm::APInt VectorSize(64, 0);
4338 if (Str.size() >= 4 && Str[0] == 'V') {
4339 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4340 size_t StrSize = Str.size();
4341 size_t VectorStringLength = 0;
4342 while ((VectorStringLength + 1) < StrSize &&
4343 isdigit(Str[VectorStringLength + 1]))
4344 ++VectorStringLength;
4345 if (VectorStringLength &&
4346 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4347 VectorSize.isPowerOf2()) {
4348 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4349 IntegerMode, ComplexMode, ExplicitType);
4350 // Avoid duplicate warning from template instantiation.
4351 if (!InInstantiation)
4352 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4353 } else {
4354 VectorSize = 0;
4355 }
4356 }
4357
4358 if (!VectorSize)
4359 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4360 ExplicitType);
4361
4362 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4363 // and friends, at least with glibc.
4364 // FIXME: Make sure floating-point mappings are accurate
4365 // FIXME: Support XF and TF types
4366 if (!DestWidth) {
4367 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4368 return;
4369 }
4370
4371 QualType OldTy;
4372 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4373 OldTy = TD->getUnderlyingType();
4374 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4375 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4376 // Try to get type from enum declaration, default to int.
4377 OldTy = ED->getIntegerType();
4378 if (OldTy.isNull())
4379 OldTy = Context.IntTy;
4380 } else
4381 OldTy = cast<ValueDecl>(D)->getType();
4382
4383 if (OldTy->isDependentType()) {
4384 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4385 return;
4386 }
4387
4388 // Base type can also be a vector type (see PR17453).
4389 // Distinguish between base type and base element type.
4390 QualType OldElemTy = OldTy;
4391 if (const auto *VT = OldTy->getAs<VectorType>())
4392 OldElemTy = VT->getElementType();
4393
4394 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4395 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4396 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4397 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4398 VectorSize.getBoolValue()) {
4399 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4400 return;
4401 }
4402 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4403 !OldElemTy->isBitIntType()) ||
4404 OldElemTy->getAs<EnumType>();
4405
4406 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4407 !IntegralOrAnyEnumType)
4408 Diag(AttrLoc, diag::err_mode_not_primitive);
4409 else if (IntegerMode) {
4410 if (!IntegralOrAnyEnumType)
4411 Diag(AttrLoc, diag::err_mode_wrong_type);
4412 } else if (ComplexMode) {
4413 if (!OldElemTy->isComplexType())
4414 Diag(AttrLoc, diag::err_mode_wrong_type);
4415 } else {
4416 if (!OldElemTy->isFloatingType())
4417 Diag(AttrLoc, diag::err_mode_wrong_type);
4418 }
4419
4420 QualType NewElemTy;
4421
4422 if (IntegerMode)
4423 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4424 OldElemTy->isSignedIntegerType());
4425 else
4426 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
4427
4428 if (NewElemTy.isNull()) {
4429 // Only emit diagnostic on host for 128-bit mode attribute
4430 if (!(DestWidth == 128 && getLangOpts().CUDAIsDevice))
4431 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4432 return;
4433 }
4434
4435 if (ComplexMode) {
4436 NewElemTy = Context.getComplexType(NewElemTy);
4437 }
4438
4439 QualType NewTy = NewElemTy;
4440 if (VectorSize.getBoolValue()) {
4441 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4443 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4444 // Complex machine mode does not support base vector types.
4445 if (ComplexMode) {
4446 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4447 return;
4448 }
4449 unsigned NumElements = Context.getTypeSize(OldElemTy) *
4450 OldVT->getNumElements() /
4451 Context.getTypeSize(NewElemTy);
4452 NewTy =
4453 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4454 }
4455
4456 if (NewTy.isNull()) {
4457 Diag(AttrLoc, diag::err_mode_wrong_type);
4458 return;
4459 }
4460
4461 // Install the new type.
4462 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4463 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4464 else if (auto *ED = dyn_cast<EnumDecl>(D))
4465 ED->setIntegerType(NewTy);
4466 else
4467 cast<ValueDecl>(D)->setType(NewTy);
4468
4469 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4470}
4471
4472static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4473 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4474}
4475
4477 const AttributeCommonInfo &CI,
4478 const IdentifierInfo *Ident) {
4479 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4480 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4481 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4482 return nullptr;
4483 }
4484
4485 if (D->hasAttr<AlwaysInlineAttr>())
4486 return nullptr;
4487
4488 return ::new (Context) AlwaysInlineAttr(Context, CI);
4489}
4490
4491InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4492 const ParsedAttr &AL) {
4493 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4494 // Attribute applies to Var but not any subclass of it (like ParmVar,
4495 // ImplicitParm or VarTemplateSpecialization).
4496 if (VD->getKind() != Decl::Var) {
4497 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4498 << AL << AL.isRegularKeywordAttribute()
4501 return nullptr;
4502 }
4503 // Attribute does not apply to non-static local variables.
4504 if (VD->hasLocalStorage()) {
4505 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4506 return nullptr;
4507 }
4508 }
4509
4510 return ::new (Context) InternalLinkageAttr(Context, AL);
4511}
4512InternalLinkageAttr *
4513Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4514 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4515 // Attribute applies to Var but not any subclass of it (like ParmVar,
4516 // ImplicitParm or VarTemplateSpecialization).
4517 if (VD->getKind() != Decl::Var) {
4518 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4519 << &AL << AL.isRegularKeywordAttribute()
4522 return nullptr;
4523 }
4524 // Attribute does not apply to non-static local variables.
4525 if (VD->hasLocalStorage()) {
4526 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4527 return nullptr;
4528 }
4529 }
4530
4531 return ::new (Context) InternalLinkageAttr(Context, AL);
4532}
4533
4535 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4536 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4537 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4538 return nullptr;
4539 }
4540
4541 if (D->hasAttr<MinSizeAttr>())
4542 return nullptr;
4543
4544 return ::new (Context) MinSizeAttr(Context, CI);
4545}
4546
4548 const AttributeCommonInfo &CI) {
4549 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4550 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4551 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4552 D->dropAttr<AlwaysInlineAttr>();
4553 }
4554 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4555 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4556 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4557 D->dropAttr<MinSizeAttr>();
4558 }
4559
4560 if (D->hasAttr<OptimizeNoneAttr>())
4561 return nullptr;
4562
4563 return ::new (Context) OptimizeNoneAttr(Context, CI);
4564}
4565
4566static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4567 if (AlwaysInlineAttr *Inline =
4568 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4569 D->addAttr(Inline);
4570}
4571
4572static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4573 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4574 D->addAttr(MinSize);
4575}
4576
4577static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4578 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4579 D->addAttr(Optnone);
4580}
4581
4582static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4583 const auto *VD = cast<VarDecl>(D);
4584 if (VD->hasLocalStorage()) {
4585 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4586 return;
4587 }
4588 // constexpr variable may already get an implicit constant attr, which should
4589 // be replaced by the explicit constant attr.
4590 if (auto *A = D->getAttr<CUDAConstantAttr>()) {
4591 if (!A->isImplicit())
4592 return;
4593 D->dropAttr<CUDAConstantAttr>();
4594 }
4595 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4596}
4597
4598static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4599 const auto *VD = cast<VarDecl>(D);
4600 // extern __shared__ is only allowed on arrays with no length (e.g.
4601 // "int x[]").
4602 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4603 !isa<IncompleteArrayType>(VD->getType())) {
4604 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4605 return;
4606 }
4607 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4608 S.CUDA().DiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4609 << llvm::to_underlying(S.CUDA().CurrentTarget()))
4610 return;
4611 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4612}
4613
4614static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4615 const auto *FD = cast<FunctionDecl>(D);
4616 if (!FD->getReturnType()->isVoidType() &&
4617 !FD->getReturnType()->getAs<AutoType>() &&
4619 SourceRange RTRange = FD->getReturnTypeSourceRange();
4620 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4621 << FD->getType()
4622 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4623 : FixItHint());
4624 return;
4625 }
4626 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4627 if (Method->isInstance()) {
4628 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4629 << Method;
4630 return;
4631 }
4632 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4633 }
4634 // Only warn for "inline" when compiling for host, to cut down on noise.
4635 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4636 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4637
4638 if (AL.getKind() == ParsedAttr::AT_NVPTXKernel)
4639 D->addAttr(::new (S.Context) NVPTXKernelAttr(S.Context, AL));
4640 else
4641 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4642 // In host compilation the kernel is emitted as a stub function, which is
4643 // a helper function for launching the kernel. The instructions in the helper
4644 // function has nothing to do with the source code of the kernel. Do not emit
4645 // debug info for the stub function to avoid confusing the debugger.
4646 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
4647 D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4648}
4649
4650static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4651 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4652 if (VD->hasLocalStorage()) {
4653 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4654 return;
4655 }
4656 }
4657
4658 if (auto *A = D->getAttr<CUDADeviceAttr>()) {
4659 if (!A->isImplicit())
4660 return;
4661 D->dropAttr<CUDADeviceAttr>();
4662 }
4663 D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
4664}
4665
4666static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4667 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4668 if (VD->hasLocalStorage()) {
4669 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4670 return;
4671 }
4672 }
4673 if (!D->hasAttr<HIPManagedAttr>())
4674 D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
4675 if (!D->hasAttr<CUDADeviceAttr>())
4676 D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
4677}
4678
4679static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4680 const auto *Fn = cast<FunctionDecl>(D);
4681 if (!Fn->isInlineSpecified()) {
4682 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4683 return;
4684 }
4685
4686 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4687 S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4688
4689 D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4690}
4691
4692static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4693 if (hasDeclarator(D)) return;
4694
4695 // Diagnostic is emitted elsewhere: here we store the (valid) AL
4696 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4697 CallingConv CC;
4699 AL, CC, /*FD*/ nullptr,
4700 S.CUDA().IdentifyTarget(dyn_cast<FunctionDecl>(D))))
4701 return;
4702
4703 if (!isa<ObjCMethodDecl>(D)) {
4704 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4706 return;
4707 }
4708
4709 switch (AL.getKind()) {
4710 case ParsedAttr::AT_FastCall:
4711 D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4712 return;
4713 case ParsedAttr::AT_StdCall:
4714 D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4715 return;
4716 case ParsedAttr::AT_ThisCall:
4717 D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4718 return;
4719 case ParsedAttr::AT_CDecl:
4720 D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4721 return;
4722 case ParsedAttr::AT_Pascal:
4723 D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4724 return;
4725 case ParsedAttr::AT_SwiftCall:
4726 D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4727 return;
4728 case ParsedAttr::AT_SwiftAsyncCall:
4729 D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
4730 return;
4731 case ParsedAttr::AT_VectorCall:
4732 D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4733 return;
4734 case ParsedAttr::AT_MSABI:
4735 D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4736 return;
4737 case ParsedAttr::AT_SysVABI:
4738 D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4739 return;
4740 case ParsedAttr::AT_RegCall:
4741 D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4742 return;
4743 case ParsedAttr::AT_Pcs: {
4744 PcsAttr::PCSType PCS;
4745 switch (CC) {
4746 case CC_AAPCS:
4747 PCS = PcsAttr::AAPCS;
4748 break;
4749 case CC_AAPCS_VFP:
4750 PCS = PcsAttr::AAPCS_VFP;
4751 break;
4752 default:
4753 llvm_unreachable("unexpected calling convention in pcs attribute");
4754 }
4755
4756 D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4757 return;
4758 }
4759 case ParsedAttr::AT_AArch64VectorPcs:
4760 D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4761 return;
4762 case ParsedAttr::AT_AArch64SVEPcs:
4763 D->addAttr(::new (S.Context) AArch64SVEPcsAttr(S.Context, AL));
4764 return;
4765 case ParsedAttr::AT_AMDGPUKernelCall:
4766 D->addAttr(::new (S.Context) AMDGPUKernelCallAttr(S.Context, AL));
4767 return;
4768 case ParsedAttr::AT_IntelOclBicc:
4769 D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4770 return;
4771 case ParsedAttr::AT_PreserveMost:
4772 D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4773 return;
4774 case ParsedAttr::AT_PreserveAll:
4775 D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4776 return;
4777 case ParsedAttr::AT_M68kRTD:
4778 D->addAttr(::new (S.Context) M68kRTDAttr(S.Context, AL));
4779 return;
4780 case ParsedAttr::AT_PreserveNone:
4781 D->addAttr(::new (S.Context) PreserveNoneAttr(S.Context, AL));
4782 return;
4783 case ParsedAttr::AT_RISCVVectorCC:
4784 D->addAttr(::new (S.Context) RISCVVectorCCAttr(S.Context, AL));
4785 return;
4786 default:
4787 llvm_unreachable("unexpected attribute kind");
4788 }
4789}
4790
4791static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4792 if (AL.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress) {
4793 // Suppression attribute with GSL spelling requires at least 1 argument.
4794 if (!AL.checkAtLeastNumArgs(S, 1))
4795 return;
4796 }
4797
4798 std::vector<StringRef> DiagnosticIdentifiers;
4799 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4800 StringRef RuleName;
4801
4802 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4803 return;
4804
4805 DiagnosticIdentifiers.push_back(RuleName);
4806 }
4807 D->addAttr(::new (S.Context)
4808 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
4809 DiagnosticIdentifiers.size()));
4810}
4811
4812static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4813 TypeSourceInfo *DerefTypeLoc = nullptr;
4814 QualType ParmType;
4815 if (AL.hasParsedType()) {
4816 ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
4817
4818 unsigned SelectIdx = ~0U;
4819 if (ParmType->isReferenceType())
4820 SelectIdx = 0;
4821 else if (ParmType->isArrayType())
4822 SelectIdx = 1;
4823
4824 if (SelectIdx != ~0U) {
4825 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
4826 << SelectIdx << AL;
4827 return;
4828 }
4829 }
4830
4831 // To check if earlier decl attributes do not conflict the newly parsed ones
4832 // we always add (and check) the attribute to the canonical decl. We need
4833 // to repeat the check for attribute mutual exclusion because we're attaching
4834 // all of the attributes to the canonical declaration rather than the current
4835 // declaration.
4836 D = D->getCanonicalDecl();
4837 if (AL.getKind() == ParsedAttr::AT_Owner) {
4838 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
4839 return;
4840 if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
4841 const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
4842 ? OAttr->getDerefType().getTypePtr()
4843 : nullptr;
4844 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4845 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4846 << AL << OAttr
4847 << (AL.isRegularKeywordAttribute() ||
4848 OAttr->isRegularKeywordAttribute());
4849 S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
4850 }
4851 return;
4852 }
4853 for (Decl *Redecl : D->redecls()) {
4854 Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
4855 }
4856 } else {
4857 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
4858 return;
4859 if (const auto *PAttr = D->getAttr<PointerAttr>()) {
4860 const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
4861 ? PAttr->getDerefType().getTypePtr()
4862 : nullptr;
4863 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4864 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4865 << AL << PAttr
4866 << (AL.isRegularKeywordAttribute() ||
4867 PAttr->isRegularKeywordAttribute());
4868 S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
4869 }
4870 return;
4871 }
4872 for (Decl *Redecl : D->redecls()) {
4873 Redecl->addAttr(::new (S.Context)
4874 PointerAttr(S.Context, AL, DerefTypeLoc));
4875 }
4876 }
4877}
4878
4879static void handleRandomizeLayoutAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4880 if (checkAttrMutualExclusion<NoRandomizeLayoutAttr>(S, D, AL))
4881 return;
4882 if (!D->hasAttr<RandomizeLayoutAttr>())
4883 D->addAttr(::new (S.Context) RandomizeLayoutAttr(S.Context, AL));
4884}
4885
4887 const ParsedAttr &AL) {
4888 if (checkAttrMutualExclusion<RandomizeLayoutAttr>(S, D, AL))
4889 return;
4890 if (!D->hasAttr<NoRandomizeLayoutAttr>())
4891 D->addAttr(::new (S.Context) NoRandomizeLayoutAttr(S.Context, AL));
4892}
4893
4895 const FunctionDecl *FD,
4896 CUDAFunctionTarget CFT) {
4897 if (Attrs.isInvalid())
4898 return true;
4899
4900 if (Attrs.hasProcessingCache()) {
4901 CC = (CallingConv) Attrs.getProcessingCache();
4902 return false;
4903 }
4904
4905 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4906 if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
4907 Attrs.setInvalid();
4908 return true;
4909 }
4910
4911 // TODO: diagnose uses of these conventions on the wrong target.
4912 switch (Attrs.getKind()) {
4913 case ParsedAttr::AT_CDecl:
4914 CC = CC_C;
4915 break;
4916 case ParsedAttr::AT_FastCall:
4917 CC =