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