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