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