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