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