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