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